前几天测试提了一个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;
}
2021年10月08日 16:27:26
我去饿但是撒阿斯顿阿三萨达阿德SaaS撒旦阿斯顿asd