Nginx 转发网络请求,后端获取的 ip 都为 127.0.0.1 问题

163 阅读1分钟

1. 问题

项目使用nginx做反向代理,后台获取到的请求ip都变成了127.0.0.1

2. nginx配置文件修改

location / {
   proxy_pass http://127.0.0.1:10000;
   proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

3. java代码处理

/**
 * 获取 IP地址
 * 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址
 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,
 * X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址
 */
public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}