服务公告
WAF:性能优化
发布时间:2026-04-21 18:02
一、前言
搞过的人都清楚,WAF跑着跑着就开始卡,CPU飙到80%、响应时间从几毫秒跳到几百毫秒,业务方投诉电话能把你手机打爆。这篇文章不废话,直接告诉你怎么把WAF性能拉回来,包括ModSecurity、NAXSI、云WAF自建节点这些常见场景,少走弯路。
二、操作步骤
第1步:确认瓶颈在哪里,别TM瞎调
# 查看WAF进程CPU占用(NAXSI/nginx + libnginx-mod-security)
top -bn1 | grep -E 'nginx|worker' | head -5
# 输出预期
# PID USER PR NI %CPU %MEM TIME+ COMMAND
# 4532 root 20 0 78.3 2.1 2:34.12 nginx: worker
# 4531 root 20 0 65.2 1.8 1:58.45 nginx: worker
# 4530 root 20 0 61.7 1.9 1:45.33 nginx: worker
# 内存和连接数状态
ss -s
# 输出预期
# Total: 1247 (kernel: 1247)
# TCP: 1245 (estab:1180, closed:2, orphan:0, timewait:0)
# Socket pools: 1
CPU全跑满就先看规则复杂度,连接数爆炸就先看并发配置。别一上来就改参数,先搞清楚谁在拖后腿。
第2步:检查规则数量和复杂度
# ModSecurity规则数量检查
grep -c "SecRule" /etc/nginx/modsecurity.conf
# 输出预期
# 187
# 查看规则类型分布
grep "SecRule" /etc/nginx/modsecurity.conf | awk '{print $3}' | sort | uniq -c | sort -rn
# 输出预期
# 45 phase:1
# 38 phase:2
# 25 phase:3
# 79 phase:4
# 35 phase:5
# 89 phase:2
Phase2规则最耗性能,因为它要检查请求体。如果规则超过200条而且全是Phase2,你WAF不卡才怪。
第3步:关闭调试日志,这是性能杀手
# CentOS/RHEL
vim /etc/httpd/conf.d/mod_security.conf
# Ubuntu/Debian
vim /etc/modsecurity/mod_security.conf
# 检查当前日志级别
grep "SecDebugLog" /etc/modsecurity/mod_security.conf
# 输出预期
# SecDebugLog /var/log/modsec_debug.log
# SecDebugLogLevel 9
# 修改为关闭
sed -i 's/SecDebugLogLevel 9/SecDebugLogLevel 0/' /etc/modsecurity/mod_security.conf
# 验证
grep "SecDebugLogLevel" /etc/modsecurity/mod_security.conf
# 输出预期
# SecDebugLogLevel 0
生产环境开Debug日志等于自残,磁盘IO直接爆炸。如果确实要排查问题,用ctl动作临时开启,排查完立刻关掉。
第4步:规则优化,合并重复规则
# 查看高频触发的规则(生产环境运行一周后)
grep "Warning" /var/log/modsec_audit.log | awk '{print $NF}' | sort | uniq -c | sort -rn | head -10
# 输出预期
# 12457 @pmFromFile xss-snippets.data
# 8934 @rx