Nginx透传获取客户端IP地址

来源:互联网 发布:js开发工具 编辑:程序博客网 时间:2024/05/16 17:11
 

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.iteye.com/topic/1124492

0 0
原创粉丝点击