插件窝 干货文章 如何保护Nginx服务器免受DDoS攻击

如何保护Nginx服务器免受DDoS攻击

Nginx limit http 防护 643    来源:    2025-04-20

保护Nginx服务器免受DDoS攻击需要多层次的安全策略组合,以下是从基础到高级的完整解决方案:


一、基础防护措施

  1. 限制连接速率

    http {
       limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
       limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    
       server {
           location / {
               limit_req zone=req_limit burst=20 nodelay;
               limit_conn conn_limit 10;
           }
       }
    }
    
    • rate=10r/s:限制每秒10个请求。
    • burst=20:允许突发20个请求排队。
    • limit_conn:限制单个IP的并发连接数。
  2. 关闭非必要模块

    • 禁用autoindexSSI等非必需模块以减少攻击面:
    ./configure --without-http_autoindex_module --without-http_ssi_module
    
  3. 调整系统参数

    # 防止SYN洪水
    sysctl -w net.ipv4.tcp_syncookies=1
    sysctl -w net.ipv4.tcp_max_syn_backlog=2048
    

二、高级防护方案

  1. 启用Nginx缓存

    proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m inactive=60m;
    server {
       location / {
           proxy_cache my_cache;
           proxy_cache_valid 200 302 10m;
       }
    }
    
    • 缓存静态内容,减轻后端压力。
  2. 使用Fail2Ban自动封禁IP

    • 安装Fail2Ban并配置Nginx规则:
    [nginx-http-auth]
    enabled = true
    filter = nginx-http-auth
    action = iptables-multiport[name=nginx, port="http,https"]
    
  3. 启用HTTP/2和Gzip

    server {
       listen 443 ssl http2;
       gzip on;
       gzip_types text/plain application/json;
    }
    
    • HTTP/2多路复用可减少连接消耗。

三、云与第三方服务整合

  1. Cloudflare防护

    • 启用Cloudflare的"DDoS Protection"模式,配置Nginx只接受Cloudflare IP:
    set_real_ip_from 103.21.244.0/22;
    real_ip_header CF-Connecting-IP;
    
  2. AWS Shield + WAF

    • 结合AWS WAF规则(如速率限制、地理封锁)和Shield Advanced防护。

四、应急响应

  1. 快速切换至静态页

    server {
       location / {
           error_page 503 = @maintenance;
           if ($attack_condition) { return 503; }
       }
       location @maintenance {
           root /var/www/static;
           try_files /maintenance.html =503;
       }
    }
    
  2. 日志分析与实时监控

    # 实时监控异常IP
    tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
    

五、深度防御建议

  • 硬件级防护:考虑部署Arbor Networks或Radware等专用硬件。
  • Anycast网络:通过分散流量缓解攻击压力。
  • 零信任架构:对API等关键路径实施双向认证。

通过以上组合策略,可有效缓解从网络层(L3/L4)到应用层(L7)的DDoS攻击。实际部署时需根据业务流量模式调整阈值,并定期进行压力测试验证防护效果。