直奔主题,在代理服务器的Nginx配置(yourWebsite.conf)的location /中添加:
#获取客户端IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
在业务服务器的Nginx配置(yourWebsite.conf)的location中添加:
fastcgi_param HTTP_X_FORWARDED_FOR $http_x_forwarded_for;
配置到这,可以用HTTP_X_FORWARDED_FOR获取客户端真实IP,以PHP为例,$_SERVER['HTTP_X_FORWARDED_FOR'],但是remote_addr还是代理服务器的IP,接着往下配置,把remote_addr也配置成真实IP。
在业务服务器的Nginx配置(yourWebsite.conf)的location中继续添加:
set_real_ip_from 172.18.209.11/24;#这里的IP是代理服务器的IP,也可以是IP段。意思是把该IP请求过来的x_forwarded_for设为remote_addr real_ip_header X-Forwarded-For;
Tip:添加上面两行之前,需要查看Nginx是否安装了realip模块,Nginx默认是不安装的,查看命令 nginx -V ,结果如下所示,如果没有realip模块,需要先安装。
nginx version: nginx/1.14.0 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) built with OpenSSL 1.0.2k-fips 26 Jan 2017 TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx --with-select_module --with-poll_module --with-threads --with-file-aio --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-stream --with-stream=dynamic --with-stream_ssl_module --with-pcre --add-module=/usr/local/nginx_upstream_check_module-master/
至此就可以使用remote_addr获取客户端的真实地址,如PHP的$_SERVER['remote_addr']。