nginx代理,Java获取访问url

首先,在前端nginx上需要做如下配置:

location /

    proxy_set_header host                $host;

    proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;

    proxy_set_header X-real-ip           $remote_addr;

};

 

nginx会在把请求转向后台real-server前把http报头中的ip地址进行替换;这样操作完成后,real-server也需要做一些操作;


ip:

public static String getClientIp(HttpServletRequest request) {

           String ip = request.getHeader("x-forwarded-for");

     //String ip = request.getHeader("X-real-ip");

            logger.debug("x-forwarded-for = {}", ip);
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("Proxy-Client-IP"); 
               logger.debug("Proxy-Client-IP = {}", ip); 
           }
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("WL-Proxy-Client-IP");
               logger.debug("WL-Proxy-Client-IP = {}", ip);
           }
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getRemoteAddr();
               logger.debug("RemoteAddr-IP = {}", ip); 
           }
           if(StringUtils.isNotBlank(ip)) {
               ip = ip.split(",")[0];
           }
           return ip;

}

 

你可能感兴趣的:(nginx代理,Java获取访问url)