1. 一种参考方式如下:
在反向代理 (Nginx) 上配置,增加 Real-IP 字段:
location / {... proxy_set_header Real-IP $remote_addr; ...}
2. 业务系统中,获取来源 IP 的代码如下(Java 示例):
@SuppressWarnings("unchecked")
public static ClientIps getClientIpAddr(HttpServletRequest request) {
// 获取真实 ip
String ip = request.getHeader("real-ip");
if (StringUtils.isBlank(ip) || ("unknown".equalsIgnoreCase(ip.trim()))) {ip = request.getHeader("remote-host");
}
if (StringUtils.isBlank(ip) || ("unknown".equalsIgnoreCase(ip.trim()))) {ip = request.getRemoteAddr();
}
ClientIps clientIps = new ClientIps();
clientIps.setTrueIp(StringUtils.trimToEmpty(ip));
// 获取代理 ip
ip = request.getHeader("x-forwarded-for");
StringBuilder proxyIps = new StringBuilder();
if (StringUtils.isNotBlank(ip) && (StringUtils.contains(ip, ","))) {String temp = StringUtils.substringBeforeLast(ip, ",");
if (StringUtils.isNotBlank(temp)) {proxyIps.append("x-forwarded-for:");
proxyIps.append(temp);
proxyIps.append("\n");
}
}
}