apache上安装modsecurity可快速防御sql注入、xss等攻击;需先用apt或dnf安装模块,启用a2enmod或确认加载,再配置owasp crs规则集,并以detectiononly模式调试后启用secruleengine on。
apache 上装 modsecurity 是给网站加一层应用层防护的直接办法。它不替代代码安全,但能快速拦住 sql 注入、xss、路径遍历等常见攻击,特别适合已有网站、又没精力重写输入校验的场景。
安装 ModSecurity 模块
以主流 Linux 发行版为例:
- Debian/Ubuntu 系统直接用 apt 安装:
sudo apt update && sudo apt install libapache2-mod-security2 - CentOS/RHEL 8+ 需启用 EPEL 仓库后安装:
sudo dnf install epel-release -y && sudo dnf install mod_security - 安装完成后启用模块:
sudo a2enmod security2(Debian系)或确认模块已加载(RHEL系) - 重启 Apache 生效:
sudo systemctl restart apache2 或 httpd
启用并配置 OWASP CRS 规则集
ModSecurity 本身是引擎,真正起作用的是规则。推荐使用 OWASP Core Rule Set(CRS),它覆盖主流攻击类型且持续更新:
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- 下载 CRS 到规则目录(如 /etc/modsecurity/crs/):
sudo git clone https://github.com/coreruleset/coreruleset /etc/modsecurity/crs - 复制示例配置:
sudo cp /etc/modsecurity/crs/crs-setup.conf.example /etc/modsecurity/crs/crs-setup.conf - 在主 ModSecurity 配置文件(通常是 /etc/modsecurity/modsecurity.conf)中,确保以下行未被注释:
IncludeOptional /etc/modsecurity/crs/rules/*.conf
Include /etc/modsecurity/crs/crs-setup.conf - 建议先设为“检测模式”(SecRuleEngine DetectionOnly),观察日志再切到 On
验证与基础调优
装完不等于生效,必须检查关键点:
- 确认模块已加载:
apache2ctl -M | grep security(Debian)或 httpd -M | grep security(RHEL) - 查看审计日志确认拦截记录:
tail -f /var/log/apache2/modsec_audit.log -
防火墙需放行 80/443 端口;若启用了 SELinux,可能需要调整策略:
sudo setsebool -P httpd_can_network_connect 1 - 首次运行建议用简单测试触发规则(如访问 /test.php?id=1%20UNION%20SELECT),看是否记入日志










