Nginx转发请求获取不到请求方真实ip

业务需要,获取请求方的ip,代码实现

 public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                                                                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        
        return ipAddress;
    }

但实际操作过程中获取的都是云服务器自身的ip
Nginx转发请求获取不到请求方真实ip_第1张图片
云服务器的ip
Nginx转发请求获取不到请求方真实ip_第2张图片
客户端实际ip是:
Nginx转发请求获取不到请求方真实ip_第3张图片
请求转发用的是Nginx,考虑可能是没有将请求方真实ip传递给后端
修改配置文件nginx.conf

location /api {
        proxy_pass http://127.0.0.1:8181/;
        #以下为新增
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;  #获取客户端真实IP
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

修改后保存,检测文件是否正常

/usr/local/nginx/sbin/nginx -t

没问题,重新加载文件

/usr/local/nginx/sbin/nginx -s reload

再测试就没问题了

你可能感兴趣的:(云服务器,Linux,nginx,Nginx,代理,ip)