nginx轉發(fā)後(hòu)後(hòu)端怎麼(me)獲取用戶真實IP
2021-07-14
經(jīng)常有需求要獲取訪問用戶的IP,在經(jīng)過(guò)nginx轉發(fā)後(hòu)真實IP就(jiù)被(bèi)隐藏起(qǐ)來了,我們需要在頭部信息裡(lǐ)拿真實IP,下面(miàn)是拿IP的代碼,考慮了各種(zhǒng)情況。
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-real-ip"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("x-forwarded-for"); if (ip != null) { ip = ip.split(",")[0].trim(); } } 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(); } return ip; }
但是後(hòu)面(miàn)還(hái)是一直拿不到真實的IP,基本上拿到的都(dōu)是127.0.0.1 後(hòu)面(miàn)我把請求頭都(dōu)輸出來了 我們在控制台把所有請求頭輸出來看看 獲取請求頭代碼
Enumeration<String> h = request.getHeaderNames();while(h.hasMoreElements()){ String n = h.nextElement(); System.out.println(n+"==="+request.getHeader(n));}
輸出結果如下
host===127.0.0.1:8080 connection===close cache-control===max-age=0 upgrade-insecure-requests===1 user-agent===Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 accept===text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 referer===http://cxytiandi.com/navigation accept-encoding===gzip, deflate, sdch accept-language===zh-CN,zh;q=0.8
發(fā)現确實真實IP沒(méi)有被(bèi)帶過(guò)來,我用的是nginx的默認配置,是不會(huì)帶過(guò)來的。
需要添加轉發(fā)的配置,將(jiāng)用戶真實的IP設置到請求頭中,然後(hòu)帶過(guò)來。
在nginx.conf中的location中增加如下代碼:
proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host;
然後(hòu)再次請求就(jiù)能(néng)看到輸出的請求頭的信息就(jiù)多了一個x-forwarded-for。 真實IP被(bèi)帶過(guò)來了。
x-forwarded-for===124.15.252.240 host===cxytiandi.com connection===close cache-control===max-age=0 upgrade-insecure-requests===1 user-agent===Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 accept===text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 referer===http://cxytiandi.com/navigation accept-encoding===gzip, deflate, sdch accept-language===zh-CN,zh;q=0.8
來源:tencent