tomcat通过nginx配置代理后IP地址获取处理

今天在配置nginx的反向代理时,配置后访问成功,但tomcat中通过request.getRemoteAddr()的地方,其IP地址始终为nginx所在的服务器地址,并不是客户端的真实地址。为了解决此问题,我百度进行了参考,地址如下:

https://blog.csdn.net/qq_38243970/article/details/78983928

https://blog.csdn.net/fly_leopard/article/details/80571286

通过这2篇文章的介绍,我首先将nginx代理服务器的配置进行设置

在配置代理的location下进入如下几句配置加入:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; #获取真实ip
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

我的配置如下图:

然后需要在tomcat的服务器上对conf下的server.xml进行配置;

找到<Host>节点,在Host里面中的默认的上面加入如下配置:

<Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Real-IP" />

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>

然后重启tomcat,最后再通过nginx访问,IP已能正常得到。

原文地址:https://www.cnblogs.com/kxxx/p/12009569.html