原文:http://blog.csdn.net/a936676463/article/details/8961504
server {
listen 80;
server_name localhost;
location /{
root html;
index index.html index.htm;
proxy_pass http://backend;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-For $http_x_forwarded_for;
}
方案1
nginx这里作一个赋值操作,如下:
proxy_set_header X-real-ip $remote_addr;
其中这个X-real-ip是一个自定义的变量名,名字可以随意取,这样做完之后,用户的真实ip就被放在X-real-ip这个变量里了,然后,在web端可以这样获取:
request.getAttribute("X-real-ip")
方案2
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
$proxy_add_x_forwarded_for的值是什么的呢?分下面两种情况
如果$http_x_forwarded_for为空: $proxy_add_x_forwarded_for = $http_x_forwarded_for + ',' + $remote_addr
如果$http_x_forwarded_for不为空: $proxy_add_x_forwarded_for = $remote_addr
其中$http_x_forwarded_for就是nginx接受到的http request header中的X-Forwarded-For的值,http request header中没有X-Forwarded-For这个header,那$http_x_forwarded_for为空
$remote_addr是直接与nginx通信的那台主机的ip。