- 在 Nginx 配置文件中加入以下内容:
geo $china {
default 0;
include geoip/GeoIP_country_CN.conf;
}
if ($china = 1) {
return 403;
}
- 下载 GeoIP 数据库:
在 /etc/nginx/ 目录下新建 geoip 文件夹,并在其内部创建 GeoIP_country_CN.conf 文件,其内容如下:
# GeoIP Country database
# Place this in /etc/nginx/geoip/
# and in your /etc/nginx/nginx.conf
# add include /etc/nginx/geoip/GeoIP_country_CN.conf;
#
# 使用 GeoLite2-Country 数据库
# 下载地址:https://dev.maxmind.com/geoip/geoip2/geolite2/
# 解压后得到 GeoLite2-Country.mmdb 文件
geoip_country /etc/nginx/geoip/GeoLite2-Country.mmdb;
map $geoip_country_code $allowed_country {
default no;
CN yes;
}
- 配置 Nginx:
在 Nginx 的配置文件中的 server 部分加入以下配置:
server {
...
# 屏蔽国内访问
include geoip/GeoIP_country_CN.conf;
if ($allowed_country = no) {
return 403; # or 404, whatever is preferred
}
...
}
以上方法可以通过 GeoIP 数据库屏蔽中国国内 IP 的访问,但也有存在误判的可能性,所以需谨慎使用。