因为项目实际需求,需要后端获取真实请求ip;但后端又通过nginx做了多次转发,在获取ip时不能获取到真实IP地址。在解决该问题之前,先了解下vue前端如何获取外网ip
1.Vue前端获取外网ip
a.在公共index.html中加上,目录public/index.html下,如下图所示
2.使用
vue代码:
1.在公共index.html中加上,目录public/index.html下
2.在vue中直接调用函数即可获取
const IP = returnCitySN['cip']
console.info('========' + IP)
2.nginx多次转发获取真实ip,nginx需要做相应的配置
配置代码:
以下2行重点,配置多次转发时,把真实ip设置在header中
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
如下图所示:
配置代码:
location /api {
// 以下2行重点,配置多次转发时,把真实ip设置在header中
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 30m;
proxy_pass_header Set-Cookie;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_pass http://ip:port;
}
3.java后端代码
java代码如下图所示:
java代码:
@ApiOperation("ip")
@GetMapping("/ip")
public String test(HttpServletRequest request) {
String forwardedIp = request.getHeader("X-Forwarded-For");
String ip;
if (!StringUtils.isEmpty(forwardedIp)) {
String[] forwardedIpSp = forwardedIp.split(",");
ip = forwardedIpSp[0];
} else {
ip = request.getHeader("X-Real-IP");
}
if (StringUtils.isEmpty(ip)) {
ip = request.getRemoteAddr();
}
log.info("===== {}", ip);
return ip;
}
4.相关大数据学习demo地址:
https://github.com/carteryh/big-data