1. 程式人生 > >通過nginx反向代理,Tomcat獲取真實的客戶端IP而非伺服器IP

通過nginx反向代理,Tomcat獲取真實的客戶端IP而非伺服器IP

通過nginx反向代理,就獲取不到真實ip,是獲取的nginx的ip,要得到真實的IP要進行配置Nginx的配置檔案: nginx.conf

proxy_set_header   X-Real-IP $remote_addr;

例如:

########################################################################
#要轉發地域名:
upstream t.csdn.com {

        server 192.168.1.188:8080 max_fails=0 weight=1; #8080為tomcat埠

    }

##################################################################
        server {
        listen 80;
        server_name t.csdn.com;
        access_log /data/wwwlogs/access_tomcat.log combined;
        root /usr/local/tomcat/webapps;
        index index.html index.jsp;

        #反向代理配置,將所有請求為http://hostname的請求全部轉發到upstream中定義的目標伺服器中。
        location / {

            #此處配置的域名必須與upstream的域名一致,才能轉發。

            proxy_pass     http://t.csdn.com;

            proxy_set_header   X-Real-IP $remote_addr;

            }   

         #啟用nginx status 監聽頁面

        location /nginxstatus {

            stub_status on;

            access_log on;

        }


        }

然後Tomcat 的獲取方式:  java
private static String getRemoteAddrIp(HttpServletRequest request) {
		String ipFromNginx = getHeader(request, "X-Real-IP");
		log.info("ipFromNginx:" + ipFromNginx);
		log.info("getRemoteAddr:" + request.getRemoteAddr());
		return StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr()
				: ipFromNginx;
	}

	private static String getHeader(HttpServletRequest request, String headName) {
		String value = request.getHeader(headName);
		return (StringUtils.isNotBlank(value) && !"unknown"
				.equalsIgnoreCase(value)) ? value : "";
	}

最後,呼叫 getRemoteAddrIp這個方法就可以得到IP:
String clientIp = getRemoteAddrIp(request);

log.info("客戶IP:" + clientIp);