天天看點

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;

}