部署waf可有效防护api安全,推荐在linux下用modsecurity集成nginx,结合owasp crs规则集,针对json接口优化规则,启用日志监控并持续调优,形成多层防御体系。

在 Linux 环境中部署 Web 应用防火墙(WAF)是保护 API 服务免受常见攻击(如 SQL 注入、跨站脚本、恶意爬虫等)的关键措施。直接暴露在公网的 API 接口极易成为攻击目标,仅靠传统防火墙无法应对应用层威胁。通过部署 WAF,可以实现对 HTTP/HTTPS 流量的深度检测与过滤,有效提升 API 的安全性。
选择合适的 WAF 解决方案
开源或商业 WAF 各有优势,应根据实际需求选择:
- ModSecurity + Nginx/Apache:最流行的开源 WAF 引擎,支持 OWASP Core Rule Set(CRS),可定制规则丰富,适合需要灵活控制的场景。
- Cloudflare / AWS WAF / Alibaba Cloud WAF:云服务商提供的托管型 WAF,配置简单,集成 CDN 和 DDoS 防护,适合快速上线且运维资源有限的团队。
- Coraza(原 Coreruleset 项目):Go 编写的 ModSecurity 兼容引擎,轻量高效,适合现代微服务架构。
对于自建 Linux 服务器环境,推荐使用 ModSecurity 集成到 Nginx 中,兼顾性能与控制力。
在 Nginx 中部署 ModSecurity WAF
以下是在基于 Linux 的 Nginx 服务器上部署 ModSecurity 的关键步骤:
1. 安装依赖和编译环境
以 Ubuntu/Debian 为例:
apt update apt install -y git build-essential autoconf automake libtool libcurl4-openssl-dev \ liblua5.3-dev libpcre3-dev libgeoip-dev libssl-dev apache2-dev libxml2-dev libyajl-dev </font><p><font color="#0066cc">2. 下载并编译 ModSecurity</font></p><p>获取 v3 分支源码并构建:</p><pre class="brush:php;toolbar:false;"> git clone https://github.com/SpiderLabs/ModSecurity.git cd ModSecurity git submodule init git submodule update ./build.sh ./configure make -j$(nproc) make install
3. 编译 Nginx with ModSecurity 模块
下载 Nginx 源码并添加动态模块支持:
git clone https://github.com/SpiderLabs/ModSecurity-nginx.git
# 编译 Nginx 时添加 --add-dynamic-module=ModSecurity-nginx
./configure --with-compat --add-dynamic-module=../ModSecurity-nginx \
--prefix=/etc/nginx --sbin-path=/usr/sbin/nginx
make modules
make install
4. 配置 ModSecurity 规则集
启用 OWASP CRS 规则:
git clone https://github.com/coreruleset/coreruleset.git /etc/nginx/crs cp /etc/nginx/crs/crs-setup.conf.example /etc/nginx/crs/crs-setup.conf
在 Nginx server 块中启用 WAF:
modsecurity on; modsecurity_rules_file /etc/nginx/modsec/main.conf;
main.conf 示例内容:
Include /etc/nginx/crs/crs-setup.conf Include /etc/nginx/crs/rules/*.conf
针对 API 服务优化 WAF 规则
API 多为 JSON 格式通信,需调整默认规则避免误拦截:
- 关闭或调低对 HTML 标签的严格检查(如 XSS 规则),防止误判合法 JSON 数据。
- 启用 JSON 请求体解析:
SecRuleEngine DetectionOnly初始阶段建议只记录不阻断。 - 为 API 路径设置例外规则,例如允许特定 POST 请求携带特殊字符。
- 添加自定义规则限制请求频率,防御暴力破解或爬虫攻击。
示例:为 /api/v1/login 添加限速和参数校验规则
SecRule REQUEST_URI "@beginsWith /api/v1/login" \
"id:1001,phase:1,t:none,pass,nolog, \
setvar:tx.anomaly_score_pl1=5"
日志监控与持续维护
开启 ModSecurity 日志便于排查问题:
SecAuditEngine RelevantOnly SecAuditLog /var/log/nginx/modsec_audit.log
定期检查日志中的误报条目,结合业务逻辑优化规则。可配合 ELK 或 Grafana 展示攻击趋势。同时保持 CRS 规则更新:
cd /etc/nginx/crs && git pull
基本上就这些。部署 WAF 不是“一劳永逸”的操作,需结合实际流量不断调优规则。对于高敏感 API,建议在 WAF 前增加 JWT 鉴权、IP 白名单等多层防护机制,形成纵深防御体系。










