有的时候我们需要借助Cloudflare 的安全防护功能来防止CC或者DDoS攻击,即仅允许Cloudflare CDN的IP访问我们的访问。
Nginx直接拒绝和允许IP访问代码示例如下:
location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; #Railgun IP deny all; }
如果我们仅允许Cloudflare CDN的IP访问网站,我们可以直接在nginx配置中将Cloudflare CDN的IP添加到允许的范围内。
#直接加入 # https://www.cloudflare.com/ips # IPv4 allow 103.21.244.0/22; allow 103.22.200.0/22; allow 103.31.4.0/22; allow 104.16.0.0/12; allow 108.162.192.0/18; allow 131.0.72.0/22; allow 141.101.64.0/18; allow 162.158.0.0/15; allow 172.64.0.0/13; allow 173.245.48.0/20; allow 188.114.96.0/20; allow 190.93.240.0/20; allow 197.234.240.0/22; allow 198.41.128.0/17; # IPv6 allow 2400:cb00::/32; allow 2405:8100::/32; allow 2405:b500::/32; allow 2606:4700::/32; allow 2803:f800::/32; allow 2c0f:f248::/32; allow 2a06:98c0::/29;
自动更新Cloudflare CDN的IP。手动添加Cloudflare CDN的IP到Nginx配置当中简单方便,但是一旦Cloudflare CDN的IP有变化时还得自己手动处理,我们可以创建一个脚本,定时去更新Cloudflare CDN的IP,自动添加到Nginx配置中,代码如下:
touch /usr/local/nginx/conf/allow_ip.conf #修改网站nginx配置,加入以下代码: include /usr/local/nginx/conf/allow_ip.conf; vim /data/script/allow_cf_ip.sh #!/bin/bash echo "#Cloudflare" > /usr/local/nginx/conf/allow_ip.conf; for i in `curl https://www.cloudflare.com/ips-v4`; do echo "allow $i;" >> /usr/local/nginx/conf/allow_ip.conf; done for i in `curl https://www.cloudflare.com/ips-v6`; do echo "allow $i;" >> /usr/local/nginx/conf/allow_ip.conf; done #添加定时任务 0 5 * * 1 /bin/bash /data/script/allow_cf_ip.sh
Qi 问的问题 2020年9月24日