前后端分离 nginx反向代理 获取ip错误问题

avatar 2021年09月29日14:26:58 0 121 views

前几天测试提了一个bug说获得的ip地址错误,不是她电脑的ip。

仔细一看那个ip是 nginx 所在的机器ip。

解决办法是在 nginx.conf 添加了

如下配置

proxy_set_header Host $http_host;
proxy_set_header Cookie $http_cookie;
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;

主要是看 x-forwarded-for的配置

 

完整的nginx配置如下

server {
    listen       80;
    server_name  网关域名;
    client_max_body_size 1024M;
    location / {
        proxy_pass http://xxx.xxx.xxx.xxx:xxx; ## 网关内网ip:端口
        proxy_set_header Host $http_host;
        proxy_set_header Cookie $http_cookie;
        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;
    }
}

然后执行 sbin/nginx -s reload 重启加载nginx配置

发现后台获取了2个ip地址,第一个是用户电脑的ip,第2个是nginx机器ip

解决办法就是后台代码处理下,取第一个

后台获取ip地址代码如下

/**
 * 获取当前请求对象
 * @return
 */
public static HttpServletRequest currentRequest()
{
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes == null)
	{
		return null;
	}
	return ((ServletRequestAttributes) requestAttributes).getRequest();
}

/**
 * 获取当前请求IP
 * @return
 */
public static String getIpAddr()
{
	HttpServletRequest currentRequest = currentRequest();
	if (currentRequest == null) 
	{
		return null;
	}
	String ip = currentRequest.getHeader(RequestHeaderKey.AUTHORIZATION_CLIENTIP);
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
	{
		ip = currentRequest.getHeader("x-forwarded-for");
		if(StringUtils.isNotEmpty(ip)) {
			if(ip.contains(",")) {
				ip = ip.split(",")[0];
			}
		}
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
	{
		ip = currentRequest.getHeader("Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
	{
		ip = currentRequest.getHeader("WL-Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
	{
		ip = currentRequest.getRemoteAddr();
	}
	return ip;
}

 

 

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
可以匿名评论或者登录后台评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 阿萨大撒旦

    我去饿但是撒阿斯顿阿三萨达阿德SaaS撒旦阿斯顿asd