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

文章来源:https://my.oschina.net/yysue/blog/2221374

如果觉得我的文章对你有用,请随意赞赏