nginx做反向负载均衡后端服务器获取真实客户端IP

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ai_zxc/article/details/78891019

nginx做反向负载均衡后端服务器获取真实客户端IP

Nginx代理站点配置

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

upstream serverName {    
    server  127.0.0.1:8080  weight=1;    
    }

server {
    listen       80;
    server_name  www.domain.com w-search.domain.com.cn w-member.domain.com.cn;
    location / {
        proxy_redirect off;
        proxy_buffer_size 128k;
        proxy_buffers 32 32k;
        proxy_busy_buffers_size 128k;
        proxy_temp_file_write_size 128k;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
        proxy_connect_timeout 5;
        proxy_send_timeout 30;
        proxy_read_timeout 10;
        proxy_pass http://serverName;
        proxy_next_upstream http_502 error timeout invalid_header;
    }
    # 静态站点配置
    location /webfile/ {
        alias   /data/www/web.domain.com/domain/web/site_1/;
        index  index.html;
    }
}

服务端JAVA代码

public class ClientIPUtils {
 /**
  * 在很多应用下都可能有需要将用户的真实IP记录下来,这时就要获得用户的真实IP地址,在JSP里,获取客户端的IP地
  * 址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,nginx等
  * 反向代理软件就不能获取到客户端的真实IP地址了。
  * 但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。
  * @param request
  * @return
  */

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;
       }
}

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