Nginx轉發請求後java獲取IP

1、Nginx增加配置
proxy_set_header Host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

	server{
		listen          80;               # 監聽80端口
		server_name     localhost;        # 指定服務器域名
		location / {
			index index.html index.htm;           # 指定首頁索引文件的名稱
			root dist;   # 指定服務器的默認網站根目錄位置
		}
		location /sys/ {
			proxy_pass   http://127.0.0.1:8010;
			proxy_set_header  Host $host;
			proxy_set_header  X-real-ip $remote_addr;
			proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
		}
	}

2、java獲取IP

    /**
     * 獲取請求用戶的IP地址
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.indexOf(COMMA) > 0) {
            // 對於通過多個代理的情況,第一個IP爲客戶端真實IP,多個IP按照','分割
            ip = ip.substring(0, ip.indexOf(COMMA));
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (LOCALHOST_IP.equals(ip)){
            ip = getLocalhostIp();
        }
        return ip;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章