...

nginx轉發後後端怎麽獲取用戶真實IP

2021-07-14

經常有需求要(yào / yāo)獲取訪問用戶的(de)IP,在(zài)經過nginx轉發後真實IP就(jiù)被隐藏起來(lái)了(le/liǎo),我們需要(yào / yāo)在(zài)頭部信息裏拿真實IP,下面是(shì)拿IP的(de)代碼,考慮了(le/liǎo)各種情況。


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;
}

但是(shì)後面還是(shì)一(yī / yì /yí)直拿不(bù)到(dào)真實的(de)IP,基本上(shàng)拿到(dào)的(de)都是(shì)127.0.0.1 後面我把請求頭都輸出(chū)來(lái)了(le/liǎo) 我們在(zài)控制台把所有請求頭輸出(chū)來(lái)看看 獲取請求頭代碼


Enumeration<String> h = request.getHeaderNames();while(h.hasMoreElements()){
    String n = h.nextElement();
    System.out.println(n+"==="+request.getHeader(n));}


輸出(chū)結果如下


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

發現确實真實IP沒有被帶過來(lái),我用的(de)是(shì)nginx的(de)默認配置,是(shì)不(bù)會帶過來(lái)的(de)。

需要(yào / yāo)添加轉發的(de)配置,将用戶真實的(de)IP設置到(dào)請求頭中,然後帶過來(lái)。

在(zài)nginx.conf中的(de)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;

然後再次請求就(jiù)能看到(dào)輸出(chū)的(de)請求頭的(de)信息就(jiù)多了(le/liǎo)一(yī / yì /yí)個(gè)x-forwarded-for。 真實IP被帶過來(lái)了(le/liǎo)。


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


來(lái)源:tencent