Nginx Rate Limiting: How to Block Abusive Traffic With limit_req

How Nginx Rate Limiting Works

Nginx rate limiting is the simplest way to stop one client from hammering your server. The limit_req module tracks how many requests each client makes and delays or rejects the excess. This guide shows how to block abusive traffic with Nginx rate limiting using limit_req, with zones for general traffic, login pages, and APIs. You do not need an external firewall or a paid service to get the basic protection right, and a few lines of configuration can turn a scraping bot or a brute-force attack from a server-crashing problem into background noise.

The mechanism has two parts. A limit_req_zone defines shared memory that stores a state per key, usually the client IP address. A limit_req directive inside a location applies a rate to that zone. Requests above the rate are delayed by default, and requests above the rate plus the burst allowance are rejected with HTTP 503. That distinction matters: delaying smooths a short spike from a real user, while rejecting stops a sustained flood. A Nginx rate limit set too low will annoy real visitors, so start generous and tighten only after watching the logs.

Rate limiting also pairs well with other layers. A dedicated walkthrough on using Nginx rate limiting against brute-force and scraping bots covers the bot angle in more detail, and Fail2ban can ban repeat offenders at the firewall level. For a broader view of attack types, read the guide to DDoS protection basics for a small VPS before deciding how strict your limits should be.

Define a limit_req Zone

Zones go in the http context, usually in /etc/nginx/nginx.conf outside any server block. This example creates a general zone of 10 MB that allows 10 requests per second per IP:

http {
    limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/m;
    limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;

    # ... rest of http block
}

Use $binary_remote_addr instead of $remote_addr because the binary form uses less memory, which matters when the zone tracks thousands of IPs. A 10 MB zone holds roughly 160,000 states, which is plenty for a small VPS. The login zone allows one request per minute, which is strict enough to slow password guessing without blocking a real user who mistypes once. The api zone is separate because API clients legitimately make more requests than browsers, and sharing one zone would let API traffic eat the budget for normal pages.

One warning: if your server sits behind Cloudflare or another proxy, every visitor appears to come from the proxy IP unless you restore real IPs first. Without that fix, one shared IP hits the limit for everyone. Set real_ip_header and trusted proxy ranges before relying on per-IP limits.

Apply limit_req to Locations

Apply the zone inside the server or location block where it belongs. A general limit on the whole site plus a stricter limit on the login page is a solid starting point:

server {
    server_name example.com;

    limit_req zone=general burst=20 nodelay;

    location /wp-login.php {
        limit_req zone=login burst=3 nodelay;
        # ... fastcgi_pass or proxy settings
    }

    location /api/ {
        limit_req zone=api burst=10;
    }
}

The burst parameter allows short spikes above the rate. With nodelay, burst requests are served immediately instead of being delayed, and only requests beyond rate plus burst are rejected. Without nodelay, burst requests are queued and served at the configured rate, which adds latency but never rejects a request that arrives within the burst allowance. For login pages, nodelay with a small burst is the right choice: a real user gets in fast, and a guessing script hits the wall immediately.

To block abusive traffic more firmly, return a custom status instead of the default 503. The limit_req_status directive sets the rejection code:

limit_req_status 429;

HTTP 429 tells well-behaved clients and search engines that the limit is temporary, which is better than 503 because it does not suggest the server is broken. Add this directive at the server or location level next to limit_req.

Log Rejected Requests and Tune the Limits

You cannot tune what you do not measure. Set a dedicated log format or simply watch the error log for limit messages:

sudo tail -f /var/log/nginx/error.log | grep limiting
sudo nginx -t && sudo systemctl reload nginx

Entries like “limiting requests, excess: 5.123 by zone general” tell you which zone fired and by how much. If you see legitimate users in these entries, your rate is too low. If you see the same IP hammering the login zone hundreds of times, your limit is working and Fail2ban can take over. A practical setup is to install Fail2ban for SSH and Nginx protection so repeated 429 responses turn into a firewall ban.

Tune in small steps. Raise the general rate if real traffic spikes during a sale or a viral post, and lower the login rate if guessing attempts continue. Avoid the temptation to set a single very low rate for the whole site. That punishes every visitor for the behaviour of a few bad IPs. Separate zones for separate paths are what make Nginx rate limiting usable in production rather than a blunt instrument.

Common Mistakes to Avoid

The most common mistake is defining the zone inside a server block. Zones must live in the http context, or Nginx refuses to start. The second mistake is applying the same zone name twice with different rates, which also fails the configuration test. The third is forgetting that limit_req counts requests, not connections. A page that loads 40 assets counts as 40 requests, so a rate of 10 requests per second will delay a normal page load unless the burst allowance covers it. This is why a burst of 20 with nodelay is a sensible default for a general zone.

Rate limiting also interacts with caching. Cached responses still count as requests against the zone, but they are cheap to serve, so a cached site can tolerate a higher rate than a dynamic one. If you want to understand that trade-off, read the explanation of Nginx proxy cache and FastCGI cache. Once your zones are live, revisit them monthly. Traffic patterns change, and a limit tuned for last quarter may be wrong for this one.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.