因为架构的需要采用多级 Nginx 反向代理,但是后端的程序获取到的客户端 IP 都是前端 Nginx 的 IP,问题的根源在于后端的 Nginx 在 HTTP Header 中取客户端 IP 时没有取对正确的值。
     
     同样适用于前端是 Squid 或者其他反向代理的情况。
    
     
      
       首先前端的 Nginx 要做转发客户端 IP 的配置
      
     
     :
    
proxy_pass http://localhost:8000;
# Forward the user’s IP address to Rails
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:
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
 
