Java开发中使用 request.getRemoteAddr 获取客户端 ip ,返回结果始终为127.0.0.1。原因是服务器使用了nginx反向代理。
解决办法:在nginx配置文件nginx.conf中添加 proxy_set_header x-forwarded-for $remote_addr; 如下所示:
location ~ ^/payapitest/
{
index index.action index.jsp;
proxy_set_header x-forwarded-for $remote_addr;
proxy_pass http://localhost:8080;
}
获取ip地址代码如下:
private String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
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;
}