• 在有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();
            }
  • 相关阅读:
    python函数名和左括号之间不能有空格
    linux版本选择
    filter_map
    awk统计总结
    Spring Boot + Redis 实现各种操作
    手机号正则校验
    判断windows系统
    Redis分布式锁
    shell 脚本快速部署 SpringBoot 项目
    Java主流的Http请求--原生的HttpURLConnection
  • 原文地址:https://www.cnblogs.com/moris5013/p/11282256.html
Copyright © 2020-2023  润新知