Nginx禁止国外IP访问网站

萝莉工坊 40 0

以Debian 11系统为例,使用的是腾讯云的系统模板。

1.打开Nginx的配置文件
通常,Nginx的配置文件位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf。使用文本编辑器(如vi或nano)打开配置文件。

nano /etc/nginx/nginx.conf

2. 在配置文件中添加IP黑名单规则

在 http部分中添加以下内容,用于定义IP黑名单
http {
    ...
    geoip_country /path/to/GeoIP.dat; #把这部分修改为 GeoIP.dat的具体路径
    map $geoip_country_code $allowed_country {
        default no;
        CN yes;
    }
}

腾讯云提供的Debian 11系统中自带GeoIP.dat,路径为/usr/share/GeoIP/GeoIP.dat 。其他云厂商的请各位自行检查。若没有的话,你可以从MaxMind网站下载免费的GeoIP数据文件,其中包含国家和IP地址的映射关系。

3. 修改服务器配置
在服务器配置部分(server块)中添加以下内容

server {
    ...
    if ($allowed_country = no) {
        return 403;
    }
    ...
}

这将在每次请求时检查客户端的IP地址,如果不在允许的国家列表中,将返回403 Forbidden错误。当然你也可以通过修改return 的内容来实现返回其他特定的html页面。

4. 保存配置文件并重新加载Nginx

sudo nginx -t
sudo nginx -s reload

效果展示

美国机通过修改系统hosts文件强制走国内反代机访问网站:

root@VM ~ $ curl https://46666.cn
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>防盗链提示</title>
    <!-- 添加 favicon 图标 -->
    <link rel="icon" href="https://46666.cn/wp-content/uploads/2024/11/cropped-Sliver_wolf.png" type="image/png">
</head>
<body style="text-align: center; font-family: Arial, sans-serif;">
    <h1>本站已开启防盗链</h1>
    <p>该图片仅可在 <a href="https://46666.cn" target="_blank" style="color: blue; text-decoration: underline;">萝莉工坊</a> 上展示:-)</p>
</body>
</html>

开启禁止国外IP访问网站后,返回403页面:

root@VM ~ $ curl https://46666.cn
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

 

发表评论 取消回复
表情 图片 链接 代码

分享