在使用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();
}

最新文章

  1. struts-OGNL
  2. ThinkPad L440 FN键设置
  3. POJ 1014 Dividing(多重背包)
  4. [CareerCup] 8.7 Chat Server 聊天服务器
  5. hdu 3635 Dragon Balls(加权并查集)2010 ACM-ICPC Multi-University Training Contest(19)
  6. 【转】COCOS2D-X之CCHttpRequest下载图片Demo
  7. [转载]传智播客_SQL入门
  8. ViewPager Indicator的使用方法
  9. Ubuntu 下开发环境的常规配置。
  10. 关于java的环境变量的一点总结
  11. myeclipse tomcat java.lang.OutOfMemoryError: PermGen space错误的解决方法
  12. 真机*Appium
  13. leetcode279
  14. youtube-dl 安装和用法
  15. FFT ip core
  16. Mysql系列九:使用zookeeper管理远程Mycat配置文件、Mycat监控、Mycat数据迁移(扩容)
  17. No converter found for return value of type
  18. <context:annotation-config/>和<mvc:annotation-driven/>及解决No mapping found for HTTP request with URI [/role/getRole] in DispatcherServlet with name 'springmvc-config'
  19. cnblogs修改网站图标icon
  20. Python学习-41.Python中的断言

热门文章

  1. WebAPI 跨域解决方案.
  2. EasyUI 主布局整合。
  3. STM32读取温湿度传感器DHT11和DHT21(AM2301)系列问题
  4. Win7添加php环境变量.
  5. Mysql主从复制架构实战
  6. Python内置函数(4)——min
  7. ELK学习总结(1-3)倒排索引
  8. IDEA里面创建maven项目,依赖
  9. [论文阅读] A Discriminative Feature Learning Approach for Deep Face Recognition (Center Loss)
  10. 正则-匹配IP地址