Layer 7 HTTP Flood & CC Attack Mitigation with Nginx limit_req

Stop Challenge Collapsar (CC) and bot floods targeting expensive search endpoints or login APIs using Nginx leaky-bucket rate limiting.

1. Attack Signature & Impact Analysis

Critical (Database CPU 100%)

Attackers hammer dynamic URL endpoints (e.g. /search?q=..., /api/v1/auth) with random parameters to bypass CDN caching, exhausting application worker threads and database pools.

2. Production Hardening Configuration (/etc/nginx/conf.d/rate-limiting.conf)

Deploy this validated configuration to your production server or reverse proxy:

# Define rate limit zone by real client IP (10MB memory zone holds ~160k IP addresses)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=2r/s;

# Return custom HTTP 429 Too Many Requests instead of generic 503
limit_req_status 429;

server {
    listen 443 ssl http2;
    server_name yourdomain.com;

    # Protect dynamic search and heavy computation endpoints
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        proxy_pass http://backend_upstream;
    }

    # Strict throttling on authentication / login
    location /api/login {
        limit_req zone=login_limit burst=5 nodelay;
        proxy_pass http://backend_upstream;
    }
}

3. Live Simulation & Rule Verification Command

Execute these commands to verify that traffic is actively mitigated without service downtime:

# Hammer API with ApacheBench (50 concurrent requests, total 200)
ab -n 200 -c 50 https://yourdomain.com/api/
# Check Nginx access.log for HTTP 429 responses
awk '($9 ~ /429/)' /var/log/nginx/access.log | wc -l

4. Common Misconfigurations & Troubleshooting Gotchas

⚠️ Production Caution: If your site is behind Cloudflare or a reverse proxy, you MUST use $http_cf_connecting_ip or set_real_ip_from, otherwise all visitors will share the proxy's IP and get blocked together!

5. Best Paired With (Complementary Defense Recipes)

Security engineers implementing this rule frequently deploy these complementary baselines: