VPS 只允许 Cloudflare 的 IP 访问

本文最后更新于 2019 年 8 月 30 日


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

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


编写文件

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

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

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

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 ips-v4 ips-v6
1
vim ~/Sites/UFW/update.sh
update.sh
1
2
3
4
#!/bin/bash

bash remove.sh
bash add.sh

使用

添加规则:

1
bash ~/Sites/UFW/add.sh

删除规则:

1
bash ~/Sites/UFW/remove.sh

更新规则:

1
bash ~/Sites/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