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. }  

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