nginx做反向代理負載均衡 後端服務器如何獲取用戶的IP

如果web程序需要獲取用戶IP的時候,通常使用了

HTTP_X_FORWARDED_FOR 和REMOTE_ADDR來獲取。


dim realIP
If Request.ServerVariables("HTTP_X_FORWARDED_FOR")="" Then
realIP=Request.ServerVariables("REMOTE_ADDR")
Else
realIP=Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
Response.write(realIP)

HTTP_X_FORWARDED_FOR 是http頭傳遞過來的變量,如果用戶用了代理,則該值取回來後爲用戶IP,代理服務器IP,(如果代理把用戶IP傳遞過來的話。)

REMOTE_ADDR 是web服務器的socket裏去回來的變量

如果web服務器在nginx的後端,

那麼web程序取回來的REMOTE_ADDR 就是nginx服務器的IP了,

在nginx中 配置

location location ~*\.(aspx|ashx|asp)$
{
.....
       proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;
       proxy_set_header X-real-ip $remote_addr;
....
}

把nginx上取到的$proxy_add_x_forwarded_for的值添加到X-forwarded-for(http header http_x_forwarded)

把nginx上取到的$remote_addr的值給X-real-ip(htpp_x_real_ip)

$proxy_add_x_forwarded_for  是HttpProxyModule模塊的變量;

引用官方解釋

Contains client request-header "X-Forwarded-For" with separated by comma $remote_addr. If there is no X-Forwarded-For request-header, than $proxy_add_x_forwarded_for is equal to $remote_addr

如果沒有這個請求頭的話,$proxy_add_x_forwarded_for的值爲$remote_addr

$remote_addr 是ngx_http_core_module的變量,爲client的值,


nginx做了如上設置後,web端再用

IP1=Request.ServerVariables("HTTP_X_FORWARDED_FOR"))


IP2=Request.ServerVariables("HTTP_X_REAL_IP")

就能取回來了,當然 如果用戶在沒有使用http代理的情況下這2個值相等


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章