nginx代理tomcat系统不能获取真实ip解决办法

出自:http://rguess.iteye.com/blog/2079618

nginx代理tomcat的时候,tomcat获取的客户端不是客户端传过来的ip,出现这种情况的原因很明显,nginx作为代理服务器先拦截客户端发来的请求,它再以localhost的身份转发给tomcat去处理。解决办法在nginx配置中的location节点中加入以下: 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header REMOTE-HOST $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

java可以这样获取远程ip 

Java代码  收藏代码
  1. public static String getIpAddr(HttpServletRequest request) {  
  2.         String ip = request.getHeader("x-forwarded-for");  
  3.         if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  4.             ip = request.getHeader("Proxy-Client-IP");  
  5.         }  
  6.         if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  7.             ip = request.getHeader("WL-Proxy-Client-IP");  
  8.         }  
  9.         if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
  10.             ip = request.getRemoteAddr();  
  11.         }  
  12.         return ip;  
  13. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章