距离上次更新本文已经过去了 434 天,文章部分内容可能已经过时,请注意甄别

问题说明

前几天,我给我的 artalk 上了 IP 屏蔽,只放行国内 IP,不允许任何国外的 IP 地址评论。

【Nginx】nginx 通过配置文件阻止海外 ip 访问 | 慕雪的寒舍

然后就发现了一个问题,我使用的 uptimerobot 这个在线状态监控程序是国外的,它的请求自然也是通过海外 IP 发起的,此时就会被我服务器的 nginx 拦截,导致 403,uptimerobot 认为 403 也是无法访问,service down 了。

image.png

解决

之前通过折腾,已经知道了如何使用 nginx 的配置文件来 allow 或者 deny 一系列 ip 地址,那么 uptimerobot 的这个问题也很好解决:只要我们知道 uptimerobbot 的请求来源 ip,那么将其写入一个如下类似的 nginx 配置文件,再在具体的 location 中 include,放行对应 ip 地址即可。

nginx
1
2
allow uptime-robot-ip1;
allow uptime-robot-ip2;

我在 uptimerobot 的官网找到了它们的 ip 地址列表:Locations and IPs | UptimeRobot

txt 文件也有的:

用如下脚本来实现

shell
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
rm -f IPv4.txt black_uptime_`date +%F`.conf
wget https://uptimerobot.com/inc/files/ips/IPv4.txt
# 删除原有文件每一行的回车符号
sed -i 's/\r//g' IPv4.txt

while IFS= read -r line
do
echo "allow $line;" >> black_uptime_`date +%F`.conf
done < IPv4.txt

rm -f /etc/nginx/black_uptime.conf && \
ln -s $PWD/black_uptime_`date +%F`.conf /etc/nginx/black_uptime.conf

将其写入一个 uptimerobot.sh 文件,使用如下命令执行它

plaintext
1
sh uptimerobot.sh

这个脚本会在当前目录里面下载 uptimerobot 的这个 IPv4.txt,并以 nginx 的形式写为 allow,最后在 /etc/nginx 里面创建一个软连接 /etc/nginx/black_uptime.conf 文件,文件内容如下

plaintext
1
2
3
allow 18.116.158.121;
allow 18.223.50.16;
allow 54.241.175.147;

随后我们进入 nginx 的配置文件,在对应站点配置文件的 location 里面,include 这个配置文件就可以了

nginx
1
2
3
4
5
location / {
# 允许uptimerobot的请求
include /etc/nginx/black_uptime.conf;
deny all; # 拒绝其他所有请求
}

添加之后,重启 nginx,配置就生效啦

plaintext
1
systemctl restart nginx

如下图,uptimerobot 已经可以正常请求和监看我的 artalk 评论页面了

image.png

使用类似的思路,你可以通过 nginx 实现让你的站点只允许 CDN 服务商的 IP 回源,禁止直接访问。