插件窝 干货文章 Nginx的HTTP防火墙与WAF

Nginx的HTTP防火墙与WAF

Nginx WAF ModSecurity block 319    来源:    2025-04-20

Nginx的HTTP防火墙与WAF解决方案

1. Nginx内置HTTP防火墙功能

Nginx本身提供了一些基础的HTTP防火墙功能,主要通过配置实现:

1.1 限制请求方法

location / {
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

1.2 防止SQL注入

set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
    set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
    return 403;
}

1.3 防止XSS攻击

set $block_xss 0;
if ($query_string ~ "<script") {
    set $block_xss 1;
}
if ($block_xss = 1) {
    return 403;
}

1.4 限制请求速率

limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
    location / {
        limit_req zone=one burst=5;
    }
}

2. 专业WAF解决方案

对于更高级的防护需求,可以考虑以下专业WAF方案:

2.1 ModSecurity + Nginx

ModSecurity是最流行的开源WAF之一:

  1. 安装ModSecurity:
git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule init
git submodule update
./build.sh
./configure
make
make install
  1. 安装Nginx连接器:
git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git
  1. 配置Nginx:
load_module modules/ngx_http_modsecurity_module.so;

http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
}

2.2 NAXSI (Nginx Anti XSS & SQL Injection)

NAXSI是专门为Nginx设计的轻量级WAF:

  1. 安装NAXSI:
apt-get install nginx-naxsi
  1. 基本配置:
http {
    include /etc/nginx/naxsi_core.rules;

    server {
        location / {
            SecRulesEnabled;
            DeniedUrl "/50x.html";

            CheckRule "$SQL >= 8" BLOCK;
            CheckRule "$RFI >= 8" BLOCK;
            CheckRule "$TRAVERSAL >= 4" BLOCK;
            CheckRule "$EVADE >= 4" BLOCK;
            CheckRule "$XSS >= 8" BLOCK;

            error_log /var/log/nginx/naxsi.log;
        }
    }
}

2.3 商业WAF解决方案

  • Cloudflare: 提供CDN+WAF服务
  • AWS WAF: 与ALB/CloudFront集成
  • Imperva: 企业级WAF解决方案
  • F5 BIG-IP: 高级应用安全防护

3. 最佳实践建议

  1. 分层防护:

    • 边缘防护(CDN WAF)
    • 主机防护(Nginx WAF)
    • 应用防护(代码层面)
  2. 规则更新:

    • 定期更新WAF规则
    • 根据业务定制规则
  3. 监控与日志:

    • 记录所有拦截事件
    • 设置告警机制
  4. 性能考虑:

    • 测试WAF对性能的影响
    • 考虑硬件加速方案
  5. 测试验证:

    • 定期进行渗透测试
    • 验证WAF规则有效性

4. 常见问题解决

Q: WAF导致合法请求被拦截怎么办?

A: 1. 检查WAF日志确定拦截原因 2. 添加白名单规则 3. 调整规则敏感度

Q: 如何测试WAF是否生效?

A:

# 测试XSS防护
curl -i "http://example.com/?q=<script>alert(1)</script>"

# 测试SQL注入防护
curl -i "http://example.com/?q=1' OR '1'='1"

Q: WAF性能影响大怎么办?

A: 1. 启用缓存 2. 优化规则(减少正则复杂度) 3. 考虑硬件加速 4. 对静态资源禁用WAF

通过合理配置Nginx的HTTP防火墙和WAF,可以显著提高Web应用的安全性,抵御常见网络攻击。