1. 程式人生 > >nginx前端,tomcat後端伺服器獲取客戶的真實IP,包括tomcat訪問日誌獲取真實IP的配置

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"/>