一、实际问题
在实际的项目开发和部署中,客户端并不是直接访问到服务器的服务的,而是通过反向代理的转发,发送到服务器端实现服务访问。比如通过反向代理实现路由/负载均衡等策略。这样在服务端拿到的客户端 ip 是反向代理服务器的 ip,而不是真实的客户端 ip。问题是在实际项目中,日志记录等应用场景必须使用到客户端真实 IP 地址。
二、解决办法
下面就是如何在使用Nginx代理和不使用代理的情况下获取客户端真实 IP 的解决办法,其实也比较简单,只需要两步操作。
2.1、nginx 配置
server { | |
listen 9090; | |
server_name localhost; | |
location / { | |
#保留代理之前的host 包含客户端真实的域名和端口号 | |
proxy_set_header Host $host; | |
#保留代理之前的真实客户端ip | |
proxy_set_header X-Real-IP $remote_addr; | |
#这个Header和X-Real-IP类似,但它在多级代理时会包含真实客户端及中间每个代理服务器的IP | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
#表示客户端真实的协议(http还是https) | |
proxy_set_header X-Forwarded-Proto $scheme; | |
#指定修改被代理服务器返回的响应头中的location头域跟refresh头域数值 | |
#如果使用"default"参数,将根据location和proxy_pass参数的设置来决定。 | |
#proxy_redirect [ default|off|redirect replacement ]; | |
proxy_redirect off; | |
proxy_pass http://localhost:8090; | |
} | |
} |
Java 代码测试
/*** | |
* 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP | |
*/ | |
public static String getIpAddr(HttpServletRequest request) { | |
if (request == null) { | |
return "unknown"; | |
} | |
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("X-Forwarded-For"); | |
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { | |
// 多次反向代理后会有多个IP值,第一个为真实IP。 | |
int index = ip.indexOf(','); | |
if (index != -1) { | |
ip = ip.substring(0, index); | |
} | |
} | |
} | |
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.getHeader("X-Real-IP"); | |
} | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getRemoteAddr(); | |
} | |
if("0:0:0:0:0:0:0:1".equals(ip)){ | |
return "127.0.0.1"; | |
}else { | |
if(ip.equals("127.0.0.1") || ip.equalsIgnoreCase("localhost") && StringUtils.isBlank(request.getRemoteAddr())){ | |
ip = request.getRemoteAddr(); | |
} | |
} | |
return ip; | |
} |
效果如下