Java 获取客户端ip返回127.0.0.1问题

Java开发中使用 request.getRemoteAddr 获取客户端 ip ,返回结果始终为127.0.0.1。原因是服务器使用了nginx反向代理。

解决办法:在nginx配置文件nginx.conf中添加 proxy_set_header X-Real-IP $remote_addr;

server {

location ^~ /testweb/ {
root html;
access_log on;
index index.jsp;
proxy_set_header X-Real-IP $remote_addr; //添加此项
proxy_pass http://127.0.0.1:88/testweb/;
}

}

java 代码如下:

public static String getRealIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
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;
}


你可能感兴趣的:(java)