skip to content
Logo 三七の小站

nginx 添加 ip 过滤规则

/ 3 min read

1. 下载并验证GeoIP数据库

首先,确保下载并验证 GeoLite2-Country.mmdb 文件:

Terminal window
wget https://raw.githubusercontent.com/Loyalsoldier/geoip/release/GeoLite2-Country.mmdb
sudo mv GeoLite2-Country.mmdb /usr/share/GeoIP/

2:安装GeoIP模块

确保Nginx安装了GeoIP模块。对于大多数Linux发行版,可以使用以下命令安装:

Terminal window
sudo apt-get update
sudo apt-get install libgeoip1 geoip-database
# 这个包通常包含GeoIP模块, 可以直接覆盖当前nginx, 不会删除现有nginx的配置。
sudo apt-get install nginx-extras

3:编辑Nginx配置文件

http {
# 加载GeoIP数据库
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
# 获取国家代码
$geoip2_data_country_iso_code country iso_code;
}
# 映射国家代码, 默认为no,表示不允许访问。
map $geoip2_data_country_iso_code $allowed_country {
default no;
CN yes;
}
server {
listen 80;
root /root/web/vuepress/dist; # 指定前端应用的目录
index index.html;
location / {
if ($allowed_country = no) {
# 禁止访问, 直接中断连接
return 444 ;
}
# 尝试访问静态文件,如HTML文件, 如果uri不存在,返回404错误。
try_files $uri $uri/ =404;
}
# 静态文件缓存
location ~* \.(js|css|avif|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
}

4:测试配置文件

运行以下命令测试Nginx配置文件是否有语法错误:

Terminal window
sudo nginx -t

如果测试通过,重启Nginx以应用新的配置:

Terminal window
sudo systemctl restart nginx

5. 数据库的一些其他信息

# 如只需要国家信息建议使用该库
geoip2 /usr/local/GeoIP2/GeoLite2-Country.mmdb {
$geoip2_data_country "default=China" source=$remote_addr country names en
}
# 如需要获取国家以及省份信息建议使用该库
geoip2 /usr/local/GeoIP2/GeoLite2-City.mmdb {
$geoip2_data_country "default=中国" source=$remote_addr country names zh-CN; # 中国
$geoip2_data_country_code country iso_code; # CN
$geoip2_data_country_continent continent names zh-CN; # 亚洲
$geoip2_data_country_continent_code continent code; # AS
$geoip2_data_province_name subdivisions 0 names zh-CN; # 浙江省
$geoip2_data_province_isocode subdivisions 0 names iso_code; # "ZJ"
$geoip2_data_city city names zh-CN; # 杭州
$geoip2_data_city_longitude location longitude; # 120.161200
$geoip2_data_city_latitude location latitude; # 30.299400
$geoip2_data_city_time_zone location time_zone; # "Asia/Shanghai"
}