nginx 反向代理 取得真实IP和域名

来源:互联网 发布:淘宝网长款毛衣 编辑:程序博客网 时间:2024/05/22 08:04

      nginx反向代理后,在应用中取得的ip都是反向代理服务器的ip,取得的域名也是反向代理配置的url的域名,解决该问题,需要在nginx反向代理配置中添加一些配置信息,目的将客户端的真实ip和域名传递到应用程序中。

 

     nginx反向代理配置时,一般会添加下面的配置:

      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;

 

其中第一行关于host的配置,是关于域名传递的配置,余下跟IP相关。


Java代码:

  public String getClientIP(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; } 


0 0