0
0
NginxDebug / FixBeginner · 4 min read

How to Prevent DDoS Attacks Using Nginx: Simple Steps

To prevent DDoS attacks using nginx, configure rate limiting and connection limiting to restrict excessive requests from the same IP. Use directives like limit_req_zone and limit_conn_zone to control traffic and protect your server from overload.
🔍

Why This Happens

DDoS attacks happen when many requests flood your server, making it slow or unreachable. Without limits, nginx accepts all requests, which can overload your server and cause downtime.

nginx
server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}
Output
Server accepts unlimited requests, leading to overload during attack.
🔧

The Fix

Set up limit_req_zone and limit_req to limit request rate per IP. Also use limit_conn_zone and limit_conn to limit simultaneous connections. This stops too many requests or connections from one source.

nginx
http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        listen 80;

        location / {
            limit_req zone=one burst=20 nodelay;
            limit_conn addr 10;
            proxy_pass http://backend;
        }
    }
}
Output
Requests from one IP are limited to 10 per second and max 10 connections, preventing overload.
🛡️

Prevention

Always use rate and connection limiting in nginx to protect your server. Combine with firewall rules and monitoring tools. Regularly update nginx and tune limits based on your traffic patterns to avoid blocking good users.

⚠️

Related Errors

Common issues include blocking legitimate users by setting limits too low or not handling bursts properly. Use burst and nodelay wisely to allow short spikes. Also, misconfigured zones cause errors on reload.

nginx
http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;  # Corrected rate
}
Output
nginx: [emerg] invalid rate value "0r/s" in limit_req_zone directive

Key Takeaways

Use limit_req_zone and limit_req to control request rates per IP in nginx.
Use limit_conn_zone and limit_conn to limit simultaneous connections per IP.
Tune limits carefully to avoid blocking normal users during traffic spikes.
Combine nginx limits with firewall and monitoring for better DDoS protection.
Always test nginx config after changes to avoid syntax errors and reload failures.