nginx做反向负载均衡,后端服务器获取真实客户端ip
首先,在前端nginx上需要做如下配置:
location /
proxy_set_hearder host $host;
proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header X-real-ip $remote_addr;
};
nginx会在把请求转向后台real-server前把http报头中的ip地址进行替换;这样操作完成后,real-server也需要做一些操作;
可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串Ip值,此时取第一个Ip地址就可以了,相关代码如下:
public String getClientIp(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(); } if(ip.trim().contains(",")){//为什么会有这一步,因为经过多层代理后会有多个代理,取第一个ip地址就可以了 String [] ips=ip.split(","); ip=ips[0]; } return ip; }