nginx可通过include指令结合文件更新与reload实现伪动态ip封禁:1.用include引入独立deny配置文件;2.自动化生成并原子替换ip列表;3.通过nginx -t && nginx -s reload安全重载;4.可选map+geo实现更灵活的黑白名单控制。

Nginx 本身不支持运行时动态读取并重新加载外部 IP 列表(比如从文件实时更新封禁规则),但可以通过 include 指令结合合理的文件管理与重载机制,实现“伪动态”IP 封禁——即配置变更后通过 reload 生效,无需重启进程。
1. 使用 include 引入独立的 IP 封禁配置文件
在 http 或 server 块中,用 include 加载一个专门存放 deny 规则的文件,例如:
http {
# 其他配置...
include /etc/nginx/conf.d/ip_blacklist.conf;
}
然后创建 /etc/nginx/conf.d/ip_blacklist.conf,内容格式为:
deny 192.168.1.100; deny 203.0.113.45; deny 2001:db8::1; allow all;
注意:deny 和 allow 的顺序很重要,Nginx 按照从上到下匹配,最后的 allow all 是兜底放行(否则默认全部拒绝)。
2. 自动化生成和更新封禁列表文件
把封禁 IP 来源(如日志分析脚本、威胁情报 API、防火墙同步数据)输出为标准 Nginx deny 格式,并覆盖写入 ip_blacklist.conf。示例 shell 脚本逻辑:
- 从 CSV/JSON/API 获取恶意 IP 列表
- 过滤掉非法格式(空行、非 IP 字符等)
- 每行转成
deny xxx.xxx.xxx.xxx;或deny xxxx:xxxx::xxx; - 末尾追加
allow all; - 写入目标文件(建议先写临时文件再
mv原子替换,避免 reload 时读到半截内容)
3. 安全重载配置而非重启
更新完文件后,执行 nginx -t 验证语法,再用 nginx -s reload 重新加载配置。这个过程零停机,且只生效新规则:
nginx -t && nginx -s reload
可将该命令集成进更新脚本末尾,或配合 systemd timer/cron 定期执行。
4. 可选增强:用 map 实现更灵活的黑白名单控制
如果需区分“封禁”“限速”“标记”等行为,推荐用 map + geo 模块替代简单 deny:
geo $blocked_ip {
default 0;
include /etc/nginx/conf.d/blocked_ips.map;
}
map $blocked_ip $limit_key {
1 "$binary_remote_addr";
default "";
}
limit_req zone=perip burst=5 nodelay;
其中 blocked_ips.map 内容为:
192.168.1.100 1; 203.0.113.45 1;
这种方式更易扩展,也便于后续对接 WAF 或日志标记。
不复杂但容易忽略的是:确保 Nginx 主进程有权限读取 include 文件;每次更新后必须 reload 才生效;deny 规则只对当前作用域生效(http/server/location),别漏掉 location 块里重复定义的问题。











