nginx代理,客户端获取ip为127.0.0.1处理方法
Posted L12345
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx代理,客户端获取ip为127.0.0.1处理方法相关的知识,希望对你有一定的参考价值。
在nginx的配置文件中的location下添加
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;
server { listen 80; server_name www.xxxx.com; location / { 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; client_max_body_size 2048m; proxy_pass http://localhost:8081; index index.jsp index.html index.htm; } }
在java代码里获取ip地址修改为
public static String getip(HttpServletRequest request){ String ip = request.getHeader("x-forwarded-for"); System.out.println("x-forwarded-for ip: " + ip); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if( ip.indexOf(",")!=-1 ){ ip = ip.split(",")[0]; } } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); System.out.println("Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); System.out.println("WL-Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); System.out.println("HTTP_CLIENT_IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); System.out.println("X-Real-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); System.out.println("getRemoteAddr ip: " + ip); } System.out.println("获取客户端ip: " + ip); return ip; }
————————————————
版权声明:本文为CSDN博主「victory_chao」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/victory_chao/article/details/96133111
以上是关于nginx代理,客户端获取ip为127.0.0.1处理方法的主要内容,如果未能解决你的问题,请参考以下文章
Nginx:3Nginx代理接口后导致后台获取接口都为127.0.0.1或0.0.0.0.0.0
Nginx:3Nginx代理接口后导致后台获取接口都为127.0.0.1或0.0.0.0.0.0