TA的每日心情 | 衰 2021-2-2 11:21 |
---|
签到天数: 36 天 [LV.5]常住居民I
|
首先,在前端[url=]nginx[/url]上需要做如下配置:
location /
proxy_set_hearder host $host;
proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header X-real-ip $remote_addr;
};
nginx会在把请求转向后台real-server前把http报头中的ip地址进行替换;这样操作完成后,real-server也需要做一些操作;
public class ClientIPUtils {
/**
* 在很多应用下都可能有需要将用户的真实IP记录下来,这时就要获得用户的真实IP地址,在JSP里,获取客户端的IP地
* 址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,Squid等
* 反向代理软件就不能获取到客户端的真实IP地址了。
* 但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。
* @param request
* @return
*/
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
//String ip = request.getHeader("X-real-ip");
logger.debug("x-forwarded-for = {}", ip);
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
logger.debug("Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
logger.debug("WL-Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
logger.debug("RemoteAddr-IP = {}", ip);
}
if(StringUtils.isNotBlank(ip)) {
ip = ip.split(",")[0];
}
return ip;
}
}
|
|