nginx代理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地址

public static String getIpAddr(HttpServletRequest request) {  
 String ip = request.getHeader("x-forwarded-for");  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getHeader("Proxy-Client-IP");  
 }  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getHeader("WL-Proxy-Client-IP");  
 }  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getRemoteAddr();  
 }  
 return ip;  
} 

 

server {
        listen       9099;
        server_name  localhost;
        server_tokens off;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass  http://tomcatserver1;
            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;
        }

        location /sfz {
            proxy_pass  http://localhost:8080/efs;
        }

          location ~* /pic/.*\.(jpg|gif|png|tif|img)$ {
            root   d:/pic;
        }

        location ~* /home/.*\.(mp4|webm|ogg)$ {
            root   D:/pictureFTP/video;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


    }    

 

posted @ 2022-06-19 17:09  王卫朋  阅读(590)  评论(0编辑  收藏  举报