Nginx 代理转发之后Java后台获取IP地址处理

后台获取IP地址如果配置了Nginx,那么相应的转发请求需要配置Nginx代理参数,否则获取到的都是Nginx服务器地址。

Nginx Location配置

核心配置:

            proxy_redirect    off;
            proxy_set_header  Host $host;
            proxy_set_header  X-real-ip $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;

参考地址:http://www.cnblogs.com/yum777/p/6473017.html

Java获取IP地址

 public  String getIpAddr(HttpServletRequest request)  {
        String ip  =  request.getHeader( "x-forward-for" );//负载均衡下为小写
        if (ip  ==   null   ||  ip.length()  ==   0   ||   "unknown" .equalsIgnoreCase(ip))  {
        	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;
   }

 

发布了635 篇原创文章 · 获赞 552 · 访问量 368万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览