在Nginx反向代理环境中实现Web应用程序防火墙(WAF)可以有效保护后端应用免受常见Web攻击。以下是几种主要的实现方式和技术细节。
ModSecurity是最流行的开源WAF解决方案之一,可以与Nginx集成。
安装步骤:
# 安装依赖
sudo apt-get install libmodsecurity3 libmodsecurity-dev
# 编译Nginx时添加ModSecurity支持
./configure --add-module=/path/to/ModSecurity-nginx
make && make install
基本配置:
server {
listen 80;
server_name example.com;
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
location / {
proxy_pass http://backend;
# 其他代理设置...
}
}
NAXSI是专为Nginx设计的轻量级WAF。
安装:
# 下载NAXSI源码
git clone https://github.com/nbs-system/naxsi.git
# 编译Nginx时添加NAXSI模块
./configure --add-module=/path/to/naxsi/naxsi_src
配置示例:
http {
include /etc/nginx/naxsi_core.rules;
server {
listen 80;
server_name example.com;
location / {
# 启用NAXSI
SecRulesEnabled;
# 学习模式(生产环境应关闭)
LearningMode;
# 拒绝请求时重定向
DeniedUrl "/50x.html";
proxy_pass http://backend;
}
}
}
SQL注入防护:
SecRule ARGS "@detectSQLi" "id:1000,phase:2,deny,status:403,msg:'SQL Injection Attempt'"
XSS防护:
SecRule ARGS "@detectXSS" "id:1001,phase:2,deny,status:403,msg:'XSS Attempt'"
文件包含防护:
SecRule REQUEST_URI "\.\./" "id:1002,phase:1,deny,msg:'Path Traversal Attempt'"
http {
limit_req_zone $binary_remote_addr zone=waf_limit:10m rate=10r/s;
server {
location / {
limit_req zone=waf_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
请求被错误拦截:
性能下降:
通过合理配置Nginx WAF,可以显著提高Web应用安全性,同时保持良好性能。