前后端分离 nginx反向代理 获取ip错误问题

avatar 2021年09月29日14:26:58 7 3821 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此

前几天测试提了一个bug说获得的ip地址错误,不是她电脑的ip。

仔细一看那个ip是 nginx 所在的机器ip。

解决办法是在 nginx.conf 添加了

如下配置

  1. proxy_set_header Host $http_host;
  2. proxy_set_header Cookie $http_cookie;
  3. proxy_set_header X-Real-IP $remote_addr;
  4. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  5. proxy_set_header X-Forwarded-Proto $scheme;

主要是看 x-forwarded-for的配置

 

完整的nginx配置如下

  1. server {
  2. listen 80;
  3. server_name 网关域名;
  4. client_max_body_size 1024M;
  5. location / {
  6. proxy_pass http://xxx.xxx.xxx.xxx:xxx; ## 网关内网ip:端口
  7. proxy_set_header Host $http_host;
  8. proxy_set_header Cookie $http_cookie;
  9. proxy_set_header X-Real-IP $remote_addr;
  10. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  11. proxy_set_header X-Forwarded-Proto $scheme;
  12. }
  13. }

然后执行 sbin/nginx -s reload 重启加载nginx配置

发现后台获取了2个ip地址,第一个是用户电脑的ip,第2个是nginx机器ip

解决办法就是后台代码处理下,取第一个

后台获取ip地址代码如下

  1. /**
  2. * 获取当前请求对象
  3. * @return
  4. */
  5. public static HttpServletRequest currentRequest()
  6. {
  7. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  8. if (requestAttributes == null)
  9. {
  10. return null;
  11. }
  12. return ((ServletRequestAttributes) requestAttributes).getRequest();
  13. }
  14. /**
  15. * 获取当前请求IP
  16. * @return
  17. */
  18. public static String getIpAddr()
  19. {
  20. HttpServletRequest currentRequest = currentRequest();
  21. if (currentRequest == null)
  22. {
  23. return null;
  24. }
  25. String ip = currentRequest.getHeader(RequestHeaderKey.AUTHORIZATION_CLIENTIP);
  26. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
  27. {
  28. ip = currentRequest.getHeader("x-forwarded-for");
  29. if(StringUtils.isNotEmpty(ip)) {
  30. if(ip.contains(",")) {
  31. ip = ip.split(",")[0];
  32. }
  33. }
  34. }
  35. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
  36. {
  37. ip = currentRequest.getHeader("Proxy-Client-IP");
  38. }
  39. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
  40. {
  41. ip = currentRequest.getHeader("WL-Proxy-Client-IP");
  42. }
  43. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
  44. {
  45. ip = currentRequest.getRemoteAddr();
  46. }
  47. return ip;
  48. }

 

 

 

  • 微信
  • 交流学习,资料分享
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 阿萨大撒旦

    我去饿但是撒阿斯顿阿三萨达阿德SaaS撒旦阿斯顿asd