public class WebUtil { /** * Headers about client's IP */ private static final String[] HEADERS_ABOUT_CLIENT_IP = { "X-Forwarded-For", "Proxy-Client-IP",//Apache(Weblogic Plug-In Enable)+WebLogic 搭配 "WL-Proxy-Client-IP",//Apache(Weblogic Plug-In Enable)+WebLogic 搭配 "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",//ng配置 proxy_set_header HTTP_CLIENT_IP $remote_addr; 纔有用 "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" }; public static String getClientIpAddr(HttpServletRequest request) { for (String header : HEADERS_ABOUT_CLIENT_IP) { String ip = request.getHeader(header); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)){ //return ip; //X-Forwarded-For: client1, proxy1, proxy2 String[] ips = ip.split(","); return ips[0]; } } return request.getRemoteAddr(); } }
若是沒有任何代理,REMOTE_ADDR爲客戶端ip,若是有代理則爲代理機器ip。html
爲了不上述狀況,代理服務器會增長一個x_forwarded_for頭信息。java
X-Forwarded-For: client1, proxy1, proxy2nginx
能夠看出,XFF 頭信息能夠有多個,中間用逗號分隔,第一項爲真實的客戶端ip,剩下的就是曾經通過的代理或負載均衡服務器的ip地址。服務器
HAProxy增長一下配置:option forwardfor負載均衡
配置option forwardfor except 10.1.10.0/24 能夠針對內網請求不設置x_forwarded_for。代理
Nginx代理規則增長:proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;code
nginx realip模塊保證REMOTE_ADDR中就是客戶端的真實ip。htm