多级 Nginx 传递客户端 IP

因为架构的需要采用多级 Nginx 反向代理,但是后端的程序获取到的客户端 IP 都是前端 Nginx 的 IP,问题的根源在于后端的 Nginx 在 HTTP Header 中取客户端 IP 时没有取对正确的值。
同样适用于前端是 Squid 或者其他反向代理的情况。

 

 

 

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

location / {
  proxy_pass        http://localhost:8000;

  # Forward the user's IP address to Rails
  proxy_set_header           Host $host:$server_port;
  proxy_set_header           X-Real-IP $remote_addr;
  proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;
  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;
  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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值