VPS 只允许 Cloudflare 的 IP 访问

本文最后更新于 2024 年 2 月 25 日


本文以 Debian 10 上的 80 端口为例,介绍如何在 VPS 上只允许 Cloudflare 的 IP 地址访问,本文同样完全适用于 Ubuntu 18.04。

请先参照 Debian & Ubuntu 服务器的初始化配置 一文对服务器进行各种必要的配置。本文以 sammy 用户为例,进行规则的设置,并默认已按初始化配置文章对服务器进行了配置。


编写文件

1
2
mkdir -p ~/scripts/ufw
vim ~/scripts/ufw/add.sh
~/scripts/ufw/add.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

cd ~/scripts/ufw

for ipv4 in `curl -sL https://www.cloudflare.com/ips-v4/ | tee ips-v4`
do
sudo ufw allow from $ipv4 to any port 80
done

for ipv6 in `curl -sL https://www.cloudflare.com/ips-v6/ | tee ips-v6`
do
sudo ufw allow from $ipv6 to any port 80
done
1
vim ~/scripts/ufw/remove.sh
~/scripts/ufw/remove.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash

cd ~/scripts/ufw

for ipv4 in `cat ips-v4`
do
sudo ufw delete allow from $ipv4 to any port 80
done

for ipv6 in `cat ips-v6`
do
sudo ufw delete allow from $ipv6 to any port 80
done

rm -f ips-v4 ips-v6
1
vim ~/scripts/ufw/update.sh
~/scripts/ufw/update.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

cd /root/scripts/ufw

curl -sL https://www.cloudflare.com/ips-v4/ -o ips-v4.new
curl -sL https://www.cloudflare.com/ips-v6/ -o ips-v6.new

if ! cmp -s ips-v4 ips-v4.new || ! cmp -s ips-v6 ips-v6.new || [ ! -f ips-v4 ] || [ ! -f ips-v6 ]; then
bash remove.sh
bash add.sh
fi

rm -f ips-v4.new ips-v6.new

使用

添加规则:

1
bash ~/scripts/ufw/add.sh

删除规则:

1
bash ~/scripts/ufw/remove.sh

更新规则:

1
bash ~/scripts/ufw/update.sh

References

UFW Essentials: Common Firewall Rules and Commands

How to redirect output to a file and stdout

How to only allow CloudFlare access to port 443 and/or 80

Step 4: Recommended First Steps for all Cloudflare users

IP Ranges

Mastodon