直奔主题,在代理服务器的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']。
如对本文有疑问, 点击进行留言回复!!
linux下文本编辑器vim的使用方法(复制、粘贴、替换、行号、撤销、多文件操作)
网友评论