通过java代码去获取用户的访问ip,发现不管怎么获取都是`127.0.0.1`的ip
![在这里插入图片描述](https://img-blog.csdnimg.cn/50a12b7a2c2945f9bb00927f7b3b6480.png)
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
public class IpAddressUtil {
public static String getIpAddress(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } if (ipAddress != null && ipAddress.length() > 15) { if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress = ""; }
return ipAddress; } }
|
==突然想到项目是通过nginx做转发,如果nginx转发请求后未携带请求头,那就都是本地的127.0.0.1==
1 2
| #添加如下配置,让nginx转发时,携带请求头信息 proxy_set_header x-forwarded-for $remote_addr;
|
加入以上代码后,重新加载nginx配置文件,重新登录应该就可以了。
1
| ./sbin/nginx -s reoload #重启nginx
|
再次查看解决问题!!!