我相信你也被这个问题困扰过,现在看看解决方法
我的网盘自从用上cdn后,我就发现上传用户的IP不正常,一查,都是cdn的IP😂
困扰了好长时间
后来查了一下官方文档,发现修改Nginx配置文件最为容易
只要添加以下代码即可
# 配置真实IP获取(添加了指定的所有IP网段)后面的IP是你的cdn的IP
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 127.0.0.1; # 本地代理(如Nginx反向代理)
set_real_ip_from ::1; # IPv6本地代理
# 如果是非cf-cdn,从X-Forwarded-For头中获取真实IP
real_ip_header CF-Connecting-IP;
事前确保nginx是否启用了http_realip模块。我这里是在Ubuntu 22.04中使用apt安装的nginx,已经包含了该模块。可以使用如下指令检查nginx -V输出的信息是否包含--with-http_realip_module。
nginx -V 2>&1 | grep "realip"
其中Cloudflare IP可参考https://www.cloudflare.com/ips/ 。经过查看访问日志,我的网站使用Cloudflare CDN后,所有请求来源IP均在这两个地址块范围,后面配置防火墙时也只放通了这两块地址,所以只填了这两个地址块。
最后使用nginx -t验证配置文件,nginx -s reload重新加载配置即可。
可以看到啊,也是成功的把我家IPv6搞出来了。