nginx如何获取真实客户端ip

nginx作为反向代理服务器,即代理我们的服务端,下面介绍下如何配置nginx获取真实的客户端ip

1、配置nginx.con


    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
           proxy_pass http://127.0.0.1:8080;
           root   html;
           index  index.html index.htm;

        #获取真实ip配置
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

2、在java程序中可以通过如下方式获取:

    @GetMapping(value = "/getRealIp")
    public String getRealIp(){
        log.info(request.getRemoteAddr());
        log.info(request.getRequestURL().toString());
        log.info("端口" + request.getRemotePort() + "");


        log.info("======================");
        log.info("真实ip:{}",getClientIP());

        return request.getRemoteAddr() + "\n" +
                request.getRequestURL();

    }

 /***
     * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP
     */
    public String getClientIP() {
        String fromSource = "X-Real-IP";
        String ip = request.getHeader("X-Real-IP");
        log.info("X-Real-IP 初始化值的ip:{} ", ip);
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
            fromSource = "X-Forwarded-For";
            log.info("X-Forwarded-For赋值成功ip:{} ", ip);
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            fromSource = "Proxy-Client-IP";
            log.info("Proxy-Client-IP赋值成功ip:{} ", ip);
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            fromSource = "WL-Proxy-Client-IP";
            log.info("WL-Proxy-Client-IP赋值成功ip:{} ", ip);
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            fromSource = "request.getRemoteAddr";
            log.info("RemoteAddr赋值成功ip:{} ", ip);
//        }
        return ip;
    }

这样就可以打印出真实ip了!即request.getHeader("X-Real-IP")的值

引用:

查看端口占用及释放所占用的端口_查询谷歌浏览器的端口号_JDSYDWR的博客-CSDN博客

https://blog.51cto.com/u_14020077/5836635

【网络】为什么百度查到的ip和ipconfig查到的不一样;详解公网Ip和私网ip;详解网络分类ABC;_wx5bc47e97d0ded的技术博客_51CTO博客