Nginx 负载均衡 后端服务器获取前端用户真实IP

Nginx 后端 日志文件 获取的都是 前端 负载均衡器的IP 想要获取用户的真实IP 必须 使用Nginx 的模块  http_realip_module  才行!!

1. 编译 Nginx 的时候 开启 http_realip_module 模块

./configure --user=upload --group=upload --prefix=/opt/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module

make

make install

2. 完成以后修改配置

1.

Nginx 负载均衡  功能配置项增加

proxy_set_header X-Real-IP $remote_addr;

2.

后端 WEB 里增加

set_real_ip_from   192.168.1.0/24;   #允许被信任的IP段

set_real_ip_from   192.168.2.1;   #允许被信任的IP段

real_ip_header     X-Real-IP;

添加在下面

location ~ .*.php?$

   {

后端 WEB 必须要重启 Nginx 才能生效..

完成以后 tail -f access.log  查看IP是已经是真实IP

tomcat  中  配置

1.

Nginx 负载均衡  功能配置项增加

proxy_set_header X-Forwarded-For $remote_addr;

2.

tomcat  找 到 server.xml 

查找  localhost_access_log

将 

pattern="%h %l %u %t "%r" %s %b" />

修改为

pattern="%{X-FORWARDED-FOR}i %l %u %t %r %s %b %D %q %{User-Agent}i %T" resolveHosts="false"/>

保存,修改!!

重启 tomcat  ,既可生效

原文地址:https://www.cnblogs.com/jicki/p/5546938.html