• 在有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();
            }
  • 相关阅读:
    设计模式之观察者模式
    设计模式之代理模式
    用Javascript模拟微信飞机大战游戏
    [Leetcode] Remove Duplicates from Sorted List II
    [Leetcode] Remove Duplicates from Sorted List
    [Leetcode] Remove Duplicates from Sorted Array II
    [Leetcode] Palindrome Number
    [Leetcode] Decode Ways
    [Leetcode] Climbing Stairs
    [Leetcode] Maximum Subarray
  • 原文地址:https://www.cnblogs.com/moris5013/p/11282256.html
Copyright © 2020-2023  润新知