1. 程式人生 > >nginx代理,Java獲取訪問url

nginx代理,Java獲取訪問url

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

location /

proxy_set_hearder 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也需要做一些操作;

url = request.getRequestUrl();


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;

       }