nginx反向代理获取用户真实ip

nginx做反向代理时,默认的配置后端获取到的ip都是来自于nginx,如何转发用户的真实ip到后端程序呢?如是是java后端,用request.getRemoteAddr();获取到的是nginx的ip地址,而不是用户的真实ip.

修改nginx配置,如下:

upstream www.xxx.com {
    ip_hash;
    server serving-server1.com:80;
    server serving-server2.com:80;
}

server {
    listen www.xxx.com:80;
    server_name www.xxx.com;
    location / {
        proxy_pass http://www.xxx.cn;
    }
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

在原来配置的基础上加入后面的三条指令,就可以用request.getHeader("X-Forwarded-For");获取到访客的ip了.

附: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 static 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();
}

参考

  1. nginx反向代理获取用户真实ip
  2. nginx 如何配置来获取用户真实IP
  3. How to get Client IP Address using Java
  4. Getting IP address of client
posted @ 2018-09-29 11:05  okokabcd  阅读(5176)  评论(0编辑  收藏  举报