[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
场景:
客户网站或者移动APP在请求到达后端服务之前,会经过层层代理的转发。
典型的是CDN(反向代理+Squid缓存),如果是带有安全或者WAF功能的则结构要更为复杂些。
一般的解决方案:
proxy_set_header Host $host; proxy_set_header X-real-ip
$remote_addr; proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
后端服务获取客户端真实IP的方法:
request.getAttribute("X-real-ip")
现象:
后端服务获取到的IP并不是客户端真实IP,而是某一级代理的IP。
分析:
从CDN开始,每经过一个代理做一次转发,x_forwarded_for就会在后面追加一个代理IP。请求到达nginx时,x_forwarded_for已经变成一个以逗号分隔的ip串,并且以转发顺序排序。
nginx的内置变量remote_addr仅能代表nginx的上一层代理的IP,现有的nginx配置将该值赋给X_Real_Ip,那么后端获取到的X_Real_Ip也是nginx上一层代理的IP,而不是客户端真实IP。
其他解决方法:
如果采用阿里腾讯华为百度西数等云的cdn控制台可以进行参数设置IP寻址方式,但美中不足的是不能设置user-agent请求方式(无法判断),所以只能在客户端编码的形式进行获取真实IP。