nginx的配置
nginx.conf 配置
添加如下代码
proxy_set_header X-Real-IP $remote_addr;
示例如下
代码
private String getIPAddress(HttpServletRequest request){
String ip = null;
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("X-Real-IP");
}
if (ipAddress != null && ipAddress.length() != 0) {
ip = ipAddress.split(",")[0];
}
//还是不能获取到,最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ip = request.getRemoteAddr();
}
return ip;
}