java获取nginx反向代理后浏览器的真实ip

青山 2022-01-0414:34:41
评论
646字

若用nginx做反向代理后,直接用String ip = request.getRemoteAddr();

获取的将是nginx服务器所在ip地址,不能获取浏览器真实ip地址!

第一步:在nginx中添加如下配置:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

如下图所示:

java获取nginx反向代理后浏览器的真实ip

第二步:获取真实ip地址

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();
}

这样,获取到的就是用户所在公网的ip地址了。

匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: