Fail2ban 实时监控 Nginx error.log,匹配限流拒绝或自定义标记(如[BLOCK_ME])等异常模式后立即封禁IP;需增强error.log输出真实IP与可识别信号,配置专用filter、jail及iptables动作,并通过fail2ban-regex和fail2ban-client验证生效。
Fail2ban 不是定时扫描,而是实时监控 Nginx error.log 文件,一旦匹配到预设的异常模式(如频繁 401、500 或自定义错误日志),立即调用 iptables/nftables 封禁对应 IP。关键在于日志可读性、规则精准度和动作及时性。
Nginx 错误日志默认不记录客户端 IP,需主动增强输出。在站点或 http 块中启用带 IP 的自定义 error_log 格式:
log_subrequest on;(让子请求也记入 error.log)error_log /var/log/nginx/error.log warn; 并配合应用层打点:例如 Axum/PHP 在鉴权失败时输出 [BLOCK_ME] Client: 192.168.1.100
limit_req_status 429; 已设,并在 error.log 中可见 “limiting requests” 字样新建 /etc/fail2ban/filter.d/nginx-error-block.conf,聚焦 error.log 特有内容:
failregex = ^s*[error].*client <host>.*limiting requests.*$</host>
failregex = ^s*[error].*[BLOCK_ME] Client: <host>$</host>
ignoreregex = health|10.0.0.|192.168.
在 /etc/fail2ban/jail.d/nginx-error.conf 中启用该规则:
[nginx-error-block]enabled = truefilter = nginx-error-blocklogpath = /var/log/nginx/error.logmaxretry = 3(例如 3 次限流触发即封)findtime = 60(时间窗口设为 60 秒)bantime = 1800(封禁 30 分钟,避免长期误伤)action = iptables-multiport[name=NGINX_ERR, port="http,https"]配置完成后务必验证有效性,再重启服务:
fail2ban-regex /var/log/nginx/error.log /etc/fail2ban/filter.d/nginx-error-block.conf 测试正则是否命中目标行sudo fail2ban-client reload 加载新规则sudo fail2ban-client status nginx-error-block,确认“Number of jail matches”开始增长iptables -L -n | grep NGINX_ERR 是否新增 DROP 规则