使用脚本编写Nginx规则恢复CloudFlare原始访问者 IP

本文最后更新于:2022年11月4日 下午

CloudFlare 是非常好用的免费 CDN,但是来自 CDN 的请求显示的访问者 IP 将是CDN的 IP ,而不是真实访问者的。Cloudflare 将原始访问者 IP 地址包含在 X-Forwarded-For 和 CF-Connecting-IP 标头中。我们可以通过Nginx来恢复原始访问者的 IP。

参考资料

官方文章:

Restoring original visitor IP
Cloudflare IP addresses
Getting Real IP Addresses Using CloudFlare, Nginx, and Varnish

【推荐】脚本编写nginx规则

这个脚本的前提是你的所有站点都使用cf进行保护,否则请把conf文件换个位置储存,再手动将文件include进你站点配置文件的server{}里。

新建脚本文件:

1
2
3
mkdir /root/cf_rules
vim /root/cf_rules/update_cf_ip.sh
chmod +x /root/cf_rules/update_cf_ip.sh

写入脚本内容:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
echo "#Cloudflare" > /etc/nginx/conf.d/cloudflare_ip.conf;
for i in `curl https://www.cloudflare.com/ips-v4`; do
echo "set_real_ip_from $i;" >> /etc/nginx/conf.d/cloudflare_ip.conf;
done
for i in `curl https://www.cloudflare.com/ips-v6`; do
echo "set_real_ip_from $i;" >> /etc/nginx/conf.d/cloudflare_ip.conf;
done
echo "" >> /etc/nginx/conf.d/cloudflare_ip.conf;
echo "# use any of the following two" >> /etc/nginx/conf.d/cloudflare_ip.conf;
echo "real_ip_header CF-Connecting-IP;" >> /etc/nginx/conf.d/cloudflare_ip.conf;
echo "#real_ip_header X-Forwarded-For;" >> /etc/nginx/conf.d/cloudflare_ip.conf;

运行脚本后,我们可以得到一个 /etc/nginx/conf.d/cloudflare_ip.conf 的conf文件,添加完成后使用 nginx -t 来验证配置文件是否正确,正确无误后重启或者重新载入nginx即可。

1
2
nginx -t
systemctl restart nginx

使用cron计划任务来定期更新cloudflare_ip.conf文件:

1
0 5 * * 1 /bin/bash /location/to/update_cf_ip.sh

手动恢复原始访问者 IP

首先编辑Nginx配置文件,一般为 /etc/nginx/ngnix.conf

1
vim /etc/nginx/ngnix.conf

【方案1】对CloudFalre来源请求提取真实IP

在http块中添加如下内容:

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
#Cloudflare
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;

# use any of the following two
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;
IP 截止至2022年6月28号是最新的。

最新IP列表请参考:

1
2
https://www.cloudflare.com/ips-v4
https://www.cloudflare.com/ips-v6

【方案2】对所有来源请求提取真实IP

用这个方案的前提是,你的Nginx代理的所有站点都使用了CloudFlare的CDN,而你又担心CloudFlare的IP地址产生变化,或者你觉得添加的IP太多太麻烦。那么你可以使用下面的办法:

1
2
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;

重启生效

先检测下修改后的语法有没有问题:

1
nginx -t

重启即可生效:

1
systemctl restart nginx

使用脚本编写Nginx规则恢复CloudFlare原始访问者 IP
https://pawswrite.xyz/posts/32160.html
作者
Rainbow
发布于
2022年6月15日
许可协议