在业务系统中,通常需要获取用户的真实ip地址对用户进行分析,nginx配置需要有相关的配置才行
1、nginx配置
#server模块配置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
2、后端代码获取ip地址
public class IPUtils {public static final String UNKNOW_IP = "unknown";/*** 获取IP地址** @param request 请求* @return request发起客户端的IP地址*/public static String getIP(HttpServletRequest request) {if (request == null) return "0.0.0.0";String xip = request.getHeader("X-Real-IP");String xfor = request.getHeader("X-Forwarded-For");if (StrUtil.isNotEmpty(xfor) && !UNKNOW_IP.equalsIgnoreCase(xfor)) {//多次反向代理后会有多个ip值,第一个ip才是真实ipint index = xfor.indexOf(",");if (index != -1) {return xfor.substring(0, index);} else {return xfor;}}xfor = xip;if (StrUtil.isNotEmpty(xfor) && !UNKNOW_IP.equalsIgnoreCase(xfor)) {return xfor;}if (StrUtil.isBlank(xfor) || UNKNOW_IP.equalsIgnoreCase(xfor)) {xfor = request.getHeader("Proxy-Client-IP");}if (StrUtil.isBlank(xfor) || UNKNOW_IP.equalsIgnoreCase(xfor)) {xfor = request.getHeader("WL-Proxy-Client-IP");}if (StrUtil.isBlank(xfor) || UNKNOW_IP.equalsIgnoreCase(xfor)) {xfor = request.getHeader("HTTP_CLIENT_IP");}if (StrUtil.isBlank(xfor) || UNKNOW_IP.equalsIgnoreCase(xfor)) {xfor = request.getHeader("HTTP_X_FORWARDED_FOR");}if (StrUtil.isBlank(xfor) || UNKNOW_IP.equalsIgnoreCase(xfor)) {xfor = request.getRemoteAddr();}return xfor;}
}