一,X-Forwarded-For:
1,现在CDN越来越流行,大部分网站都会经过CDN代理服务器来访问真实的服务器。
2,以往,我们通过http头中REMOTE_ADDR来获取用户的IP,但是经过CND代理,这个REMOTE_ADDR就会变成代理的IP了。
3,为了获取用户的真实IP,http后来增加了X-Forwarded-For扩展头,它的数据格式如下:
X-Forwarded-For: client, proxy1, proxy2
client为用户真实IP,proxy1,proxy2为代理的IP,大部分代理服务器在转发http请求时会添加这个扩展头。
二,http_x_forwarded_for
1,Nginx有个参数http_x_forwarded_for,保存了用户经过代理后的IP信息,就是上面提到的X-Forwarded-For
2,我们通过map来匹配用户的真实IP,如下
map $http_x_forwarded_for $clientRealIp { ## 没有通过代理,直接用 remote_addr "" $remote_addr; ## 用正则匹配,从 x_forwarded_for 中取得用户的原始IP ## 例如 X-Forwarded-For: 202.123.123.11, 208.22.22.234, 192.168.2.100,... ## 这里第一个 202.123.123.11 是用户的真实 IP,后面其它都是经过的 CDN 服务器 ~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr; }
3,输出用户真实IP和代理IP信息
location =/test_ip{ default_type "text/plain"; echo remote_add is $remote_addr; echo http_x_forwarded_for is $http_x_forwarded_for; echo clientRealIp is $clientRealIp; }
参考链接:
http://www.bzfshop.net/article/176.html
http://www.tuicool.com/articles/qaYVry
Leave a Reply