nginx支持地域拦截
- 2026-05-26 21:27:00
- admin
- 原创 20
一、nginx支持地域拦截
1、maxmind免费数据库:https://github.com/P3TERX/GeoLite.mmdb
2、maxmind工具:https://github.com/maxmind/mmdbinspect
3、maxmind依赖:https://github.com/maxmind/libmaxminddb
4、maxmind依赖:https://github.com/maxmind/MaxMind-DB-Reader-python
5、geoip2插件:https://github.com/leev/ngx_http_geoip2_module
6、安装依赖:pip install maxminddb
编译libmaxminddb:
cd libmaxminddb-1.13.3
./configure --prefix=/data/mylib/libmaxminddb --enable-static --disable-shared
make && make install
编译nginx:
./configure --with-stream \
--add-module=/data/mylib/nginx-src/ngx_http_geoip2_module-3.4 \
--with-cc-opt="-I/data/mylib/libmaxminddb/include" \
--with-ld-opt="-L/data/mylib/libmaxminddb/lib -lmaxminddb" \
--prefix=/data/mylib/nginx-1.20.2
make && make install
二、nginx支持地域拦截的配置
geo $in_white_list {
default 0;
include /data/feinen/nginx-1.20.2/cn_ips.conf; # 格式: 1.0.1.0/24 1;
}
geoip2 /data/feinen/nginx-src/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_country_code_raw country iso_code default="NEW_IP";
}
map $geoip2_country_code_raw $geoip2_country_code {
"" "NEW_IP";
default $geoip2_country_code_raw;
}
map $geoip2_country_code $allowed_country {
default 0; # 默认拦截
CN 1; # 允许中国
NEW_IP 1; # 允许新增
}
map $in_white_list$allowed_country $allow_request {
"11" 1;
"10" 1;
"01" 1;
"00" 0;
default 0;
}
if ($allow_request != 1) {
return 403 "Access denied for your region";
}