分享

Nginx透传获取客户端IP地址

 hh3755 2015-01-06

nginx.conf配置:

 

Java代码  收藏代码
  1. location / {   
  2.      proxy_pass http://127.0.0.1:8080/myweb/;  
  3.      proxy_redirect    off;  
  4.      proxy_set_header  Host             $host;  
  5.      proxy_set_header  X-Real-IP        $remote_addr;  
  6.      proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;  
  7. }  

 myweb后端获取方式:

 

Java代码  收藏代码
  1. /*** 
  2.  * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP, 
  3.  * @param request 
  4.  * @return 
  5.  */  
  6. public static String getClientIP(HttpServletRequest request) {  
  7.     String fromSource = "X-Real-IP";  
  8.     String ip = request.getHeader("X-Real-IP");  
  9.     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  10.         ip = request.getHeader("X-Forwarded-For");  
  11.         fromSource = "X-Forwarded-For";  
  12.     }  
  13.     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  14.         ip = request.getHeader("Proxy-Client-IP");  
  15.         fromSource = "Proxy-Client-IP";  
  16.     }  
  17.     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  18.         ip = request.getHeader("WL-Proxy-Client-IP");  
  19.         fromSource = "WL-Proxy-Client-IP";  
  20.     }  
  21.     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  22.         ip = request.getRemoteAddr();  
  23.         fromSource = "request.getRemoteAddr";  
  24.     }  
  25.     appLog.info("App Client IP: "+ip+", fromSource: "+fromSource);  
  26.     return ip;  
  27. }  

 参考: http://www./topic/1124492

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多