Nginx代理后服务端使用remote_addr获取真实IP

2023-05-24,,

直奔主题,在代理服务器的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/;#这里的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.
built by gcc 4.8. (Red Hat 4.8.-) (GCC)
built with OpenSSL 1.0.2k-fips Jan
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']。

Nginx代理后服务端使用remote_addr获取真实IP的相关教程结束。

《Nginx代理后服务端使用remote_addr获取真实IP.doc》

下载本文的Word格式文档,以方便收藏与打印。