服务器使用nginx做代理,通过HttpServletRequest获取请求用户真实IP地址
2024-10-15 20:59:50
在使用nginx做代理时,服务端如果直接从 X-Forwarded-For 头部获取来源IP,将获取到nginx所在的ip地址,而不是请求的真实ip地址。
如何获取请求的真实IP地址
首先,在nginx配置中添加如下配置
server {
listen ;
server_name www.wenki.info; #要访问的域名 charset utf8; location / {
proxy_pass http://server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
从nginx中将请求来源IP添加到代理请求头部,然后使用命令重新加载配置
nginx -s reload
服务端使用以下代码即可获取请求主机真实IP地址
public static String realIP(HttpServletRequest request) {
String xff = request.getHeader("x-forwarded-for");
if (xff != null) {
int index = xff.indexOf(',');
if (index != -1) {
xff = xff.substring(0, index);
}
return xff.trim();
}
return request.getRemoteAddr();
}
最新文章
- struts-OGNL
- ThinkPad L440 FN键设置
- POJ 1014 Dividing(多重背包)
- [CareerCup] 8.7 Chat Server 聊天服务器
- hdu 3635 Dragon Balls(加权并查集)2010 ACM-ICPC Multi-University Training Contest(19)
- 【转】COCOS2D-X之CCHttpRequest下载图片Demo
- [转载]传智播客_SQL入门
- ViewPager Indicator的使用方法
- Ubuntu 下开发环境的常规配置。
- 关于java的环境变量的一点总结
- myeclipse tomcat java.lang.OutOfMemoryError: PermGen space错误的解决方法
- 真机*Appium
- leetcode279
- youtube-dl 安装和用法
- FFT ip core
- Mysql系列九:使用zookeeper管理远程Mycat配置文件、Mycat监控、Mycat数据迁移(扩容)
- No converter found for return value of type
- <;context:annotation-config/>;和<;mvc:annotation-driven/>;及解决No mapping found for HTTP request with URI [/role/getRole] in DispatcherServlet with name &#39;springmvc-config&#39;
- cnblogs修改网站图标icon
- Python学习-41.Python中的断言