Nginx负载均衡时获取用户真实IP
2018-03-10 19:33:35
1253 次阅读
0 个评论
正常情况下,request请求获取用户IP的api为request.getRemoteAddr()
在负载均衡时,默认获取的就是反向代理服务器的地址
要获取真实用户ip,需做如下配置修改
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;
};
JAVA获取真实IP
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
public class RequestUtils {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(RequestUtils.class);
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
logger.info("x-forwarded-for = {}", ip);
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
logger.info("Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
logger.info("WL-Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
logger.info("RemoteAddr-IP = {}", ip);
}
if(StringUtils.isNotBlank(ip)) {
ip = ip.split(",")[0];
}
return ip;
}
}
00
相关话题
- Nginx配置WebSocket负载均衡
- Nginx根据URL实现负载均衡
- nginx负载均衡,某台tomcat宕机后集群响应缓慢
- Nginx开启https负载均衡,配置Tomcat识别http和https协议
- firewalld封禁IP配置
- Linux配置静态IP
- MySQL添加允许登录IP
- VMware Ubuntu 配置静态IP
- Redis统计今日签到用户数和用户是否签到
- SpringMVC获取Request域
- 使用Redis bitmap统计活跃用户
- Redis BitMap 统计用户活跃指标
- 解决root用户和普通用户的时区不一致的问题
- firewalld对指定IP开放指定端口的配置
- Spring Boot启动时执行指定方法