nginx转发后后端怎么获取用户真实IP
2021-07-14
经常有需求要获取访问用户的IP,在经过nginx转发后真实IP就被隐藏起来了,我们需要在头部信息里拿真实IP,下面是拿IP的代码,考虑了各种情况。
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; }
但是后面还是一直拿不到真实的IP,基本上拿到的都是127.0.0.1 后面我把请求头都输出来了 我们在控制台把所有请求头输出来看看 获取请求头代码
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
发现确实真实IP没有被带过来,我用的是nginx的默认配置,是不会带过来的。
需要添加转发的配置,将用户真实的IP设置到请求头中,然后带过来。
在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;
然后再次请求就能看到输出的请求头的信息就多了一个x-forwarded-for。 真实IP被带过来了。
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