nginx前端,tomcat后端服务器获取客户的真实IP,包括tomcat访问日志获取真实IP的配置

原文链接https://blog.csdn.net/teddy17/article/details/51744119

在安装完以nginx+tomcat的WEB服务器,使用默认的配置,会导致服务器上的日志文件,只有nginx日志能获取到客户的真实IP,而tomcat以及上面的JAVA WEB应用均不能正常获取到真正的IP地址,而仅是LOOP(回还地址127.0.0.1,或者0.0.0.0.0.0.1),会导致存入到数据库的也是如此,通过以下配置,即可以改善结果。

nginx端配置文件/etc/nginx/conf.d/default.conf
 

server {
    listen       80;
    server_name localhost;
    location /{
                        rewrite ^/web(.*)$ /$1 last;
                        proxy_pass http://localhost:8080/web/;
                        proxy_cookie_path /web /;
#以下三个proxy_set_header配置项是重点
                        proxy_set_header Host $host;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

tomcat日志配置文件$CATALINA_HOME/conf/server.xml

在host中,修改以下内容

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log." suffix=".txt"
       pattern="%{X-Real-IP}i %l %u %t %D "%r" %s %b" />

 其中X-Real-IP与NGINX中配置的要对应,此变量即是客户的真实IP,pattern的其它参数,请参考官方:http://tomcat.apache.org/tomcat-7.0-doc/config/valve.html#Access_Logging
添加以下valve

<Valve className="org.apache.catalina.valves.RemoteIpValve"
	   internalProxies="127\.0\.0\.1"
	   remoteIpHeader="x-forwarded-for"
	   remoteIpProxiesHeader="x-forwarded-by"
	   trustedProxies="127\.0\.0\.1"/>

猜你喜欢

转载自blog.csdn.net/ystyaoshengting/article/details/83415035