java 获取用户的ip都是 127.0.0.1
通过nginx反向代理,java获取ip地址时,总是127.0.0.1。是因为nginx请求的时候没有带有
request信息,设置nginx转发的时候,带上request的信息就可以了。
java代码:
/** * 先从反向代理里找IP * * @param request * @return */ public static String getIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if (ip.indexOf(",") != -1) { ip = ip.split(",")[0]; } } 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) { try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { ip = ""; } } System.out.println("获取客户端ip: " + ip); return ip; }
nginx配置:
location / { proxy_set_header x-forwarded-for $remote_addr; }