在有nginx做反向代理时候,如何获取用户真实Ip信息

在获取用户的Ip地址时,不一定可以获取到用户真实的地址信息,这要看代理服务器的类型,代理服务器有普通匿名代理服务器,高匿代理服务器,像这种情况很难获取到用户真实的Ip地址

假如用户没有使用匿名代理服务器的情况下,获取用户真实IP的步骤如下:

1  nginx修改配置文件

server {
    listen       80;
    server_name  www.xxx.cn;

    location   / {
    
        proxy_pass  http://xxxx:16000;
        proxy_http_version 1.1;
        #将用户的ip设置到请求头中,tomcat可以获取到真实的ip
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
    }

}

2 java代码中获取用户真实ip

    private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR" };

        public   String getClientIpAddress(HttpServletRequest request) {
            for (String header : IP_HEADER_CANDIDATES) {
                String ip = request.getHeader(header);
                if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                    int index = ip.indexOf(",");
                    if (index != -1) {
                        return ip.substring(0, index);
                    }
                    return ip;
                }
            }
            return request.getRemoteAddr();
        }

猜你喜欢

转载自www.cnblogs.com/moris5013/p/11282256.html