Nginx作为反向代理时传递客户端IP

  in 系统架构 

因为架构的需要采用多级 Nginx 反向代理,但是后端的程序获取到的客户端 IP 都是前端 Nginx 的 IP,问题的根源在于后端的 Nginx 在 HTTP Header 中取客户端 IP 时没有取对正确的值。同样适用于前端是 Squid 或者其他反向代理的情况。(通用的解决方案是直接取服务器的变量 HTTP_X_FORWARDED_FOR 的值即可取出客户端的真实ip地址)

首先前端的 Nginx 要做转发客户端 IP 的配置:

location / {
proxy_pass        http://localhost:8000;# Forward the user's IP address to Rails
proxy_set_header           X-Real-IP $remote_addr;
# needed for HTTPS
#  proxy_set_header           X_FORWARDED_PROTO https;
proxy_set_header           X-Forwarded-For $remote_addr;
proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header           Host $host;
proxy_redirect                off;
}

后端的 Nginx 需要安装一个 Module: NginxHttpRealIpModule ,编译的时候默认不包含此 Module,需要重新编译安装 Nginx,configure 的时候加上 –with-http_realip_module,Nginx 升级或者添加/删除 Module 时支持热切换 ,可以避免中断服务。

升级后配置 NginxHttpRealIpModule,set_real_ip_from 就是指前端 Nginx 或者 Squid 的 IP:

location / {
proxy_pass        http://localhost:8000;# Forward the user's IP address to Rails
  proxy_set_header           X-Real-IP $remote_addr;
# needed for HTTPS
#  proxy_set_header           X_FORWARDED_PROTO https;
  proxy_set_header           X-Forwarded-For $remote_addr;
  proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header           Host $host;
  proxy_redirect                off;
# NginxHttpRealIpModule
  set_real_ip_from   192.168.1.0/24;
  set_real_ip_from   192.168.2.1;
  real_ip_header     X-Real-IP;
}

最后记得 reload Nginx config.使nginx平滑过渡,应用新的配置文件.

===================================

另也有网友给的以下方法,和上面的差不多,但不需要其它的模块,只是在取ip的时候,取的服务器变量有些不一样.由于程序修改度小,所以此方法用的较多.

在nginx中设置:

proxy_set_header        Host            $host;
proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

后端程序可以从Server变量 HTTP_X_REAL_IP 和 HTTP_X_FORWARDED_FOR 中获取用户的ip地址。

HTTP_X_REAL_IP的值是nginx得到的用户REMOTE_ADDR

Logo

开源、云原生的融合云平台

更多推荐