在Nginx配置文件中(通常在server
或location
块中)添加:
location / {
deny 192.168.1.100; # 禁止单个IP
deny 192.168.1.0/24; # 禁止整个IP段
allow all; # 允许其他所有IP
# 其他配置...
}
创建黑名单文件,如/etc/nginx/blocked_ips.conf
:
deny 192.168.1.100;
deny 10.0.0.0/8;
在主配置文件中包含该文件:
http {
include /etc/nginx/blocked_ips.conf;
# 其他配置...
}
确保Nginx安装了ngx_http_geoip_module
模块:
nginx -V 2>&1 | grep -o with-http_geoip_module
下载GeoIP数据库:
# MaxMind GeoIP数据库
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
mv GeoIP.dat /usr/share/GeoIP/
配置Nginx:
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
CN yes; # 只允许中国IP
HK yes; # 香港
MO yes; # 澳门
TW yes; # 台湾
}
server {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
获取中国IP段(可以从APNIC等机构获取),保存为/etc/nginx/china_ips.conf
:
allow 1.0.1.0/24;
allow 1.0.2.0/23;
# 更多中国IP段...
deny all;
在Nginx配置中引用:
location / {
include /etc/nginx/china_ips.conf;
# 其他配置...
}
修改配置后需要重载Nginx:
nginx -t && nginx -s reload
对于动态IP或CDN情况,可能需要额外处理
GeoIP数据库需要定期更新以保持准确性
大量IP规则可能影响性能,建议使用geo
模块替代大量allow/deny
规则
可以考虑结合fail2ban等工具实现动态黑名单
http {
# GeoIP配置
geoip_country /usr/share/GeoIP/GeoIP.dat;
# 允许的国家代码
map $geoip_country_code $allowed_country {
default no;
CN yes; # 中国
HK yes; # 香港
MO yes; # 澳门
TW yes; # 台湾
}
# IP黑名单
geo $blocked_ip {
default 0;
192.168.1.100 1;
10.0.0.0/8 1;
}
server {
listen 80;
server_name example.com;
# 检查IP黑名单
if ($blocked_ip) {
return 403;
}
# 检查国家限制
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
以上配置可以根据实际需求进行调整和组合使用。