使用nginx代理,后台怎么获取真实的IP

本文介绍如何在Nginx配置文件中设置代理头信息,并提供了一段Java代码用于从HttpServletRequest请求中准确获取客户端的真实IP地址。通过在nginx.conf中添加特定的proxy_set_header指令,可以确保后端应用能够接收到正确的客户端IP,这对于日志记录、访问统计及安全防护至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在nginx.conf配置中加入配置信息

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;
proxy_set_header X-NginX-Proxy true;

2.然后再后台获取真实IP

public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) || LOCALHOST.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("IPUtils ERROR ", e);
        }

        //        //使用代理,则获取第一个IP地址
        //        if(StringUtils.isEmpty(ip) && ip.length() > 15) {
        //          if(ip.indexOf(",") > 0) {
        //              ip = ip.substring(0, ip.indexOf(","));
        //          }
        //      }

        return ip;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值