java 获取通过n'gin'x代理客户端ip
时间: 2023-04-02 16:05:18 浏览: 112
Gin-Rummy-Card-Game
可以使用HttpServletRequest的getRemoteAddr()方法获取客户端IP地址,但是如果使用了Nginx代理,需要在Nginx配置中添加以下内容:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
然后在Java代码中使用以下方法获取真实的客户端IP地址:
String ip = request.getHeader("X-Real-IP");
if (ip == null || ip.length() == || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
阅读全文