Nginx负载均衡时获取用户真实IP
2018-03-10 19:33:35
752次阅读
0个评论

正常情况下,request请求获取用户IP的api为request.getRemoteAddr() 

在负载均衡时,默认获取的就是反向代理服务器的地址 

要获取真实用户ip,需做如下配置修改 


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; 

};
JAVA获取真实IP
import javax.servlet.http.HttpServletRequest;  
  
import org.apache.commons.lang.StringUtils;  
import org.slf4j.LoggerFactory;  
  
public class RequestUtils {  
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(RequestUtils.class);  
      
    public static String getClientIp(HttpServletRequest request) {  
  
        String ip = request.getHeader("x-forwarded-for");  
  
        logger.info("x-forwarded-for = {}", ip);  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");   
            logger.info("Proxy-Client-IP = {}", ip);   
        }  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
            logger.info("WL-Proxy-Client-IP = {}", ip);  
        }  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
            logger.info("RemoteAddr-IP = {}", ip);   
        }  
        if(StringUtils.isNotBlank(ip)) {  
            ip = ip.split(",")[0];  
        }  
        return ip;  
  
    }  
      
}



收藏 0 0

登录 后评论。没有帐号? 注册 一个。

admin

官方人员
  • 0 回答
  • 0 粉丝
  • 0 关注