Posted by

Nginx Rate Limiting with limit_req: Protect Login Pages and APIs with Zones, Burst and 429

Login forms, password-reset pages, search endpoints and APIs are easy targets for automated traffic. A bot can try thousands of passwords or hit an expensive page again and again until PHP-FPM or your app server runs out of workers. Nginx has a built-in answer: the ngx_http_limit_req_module, which limits how many requests a single client can make per second or per minute.

This guide shows how to add rate limiting safely on a typical Ubuntu or Debian server: how the directives work, what burst and nodelay really do, how to test in dry-run mode first, and the common mistakes that block real users. It continues our server-hardening series, which also covers SSH hardening, UFW, Fail2ban, Certbot and Nginx security headers.

How Nginx rate limiting works

The module uses the "leaky bucket" method. You define a shared memory zone that keeps a state for each key (usually the client IP address) and a rate such as 10 requests per second. Nginx then processes requests from each key at that steady rate. Requests that arrive faster than the rate are either queued (if you allow a burst) or rejected.

Two directives do the work:

  • limit_req_zone defines the key, the zone name and size, and the rate. It is only valid in the http block.
  • limit_req applies a zone to the http, server or location where you want the limit.

Step 1: Define a zone

On Ubuntu and Debian, files in /etc/nginx/conf.d/ are included inside the http block of /etc/nginx/nginx.conf, so a separate file there is a clean place for zones. Create /etc/nginx/conf.d/rate-limits.conf:

# One state per client IP, 10 MB of memory, 10 requests per second
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;

# A much stricter zone for login and password-reset pages: 5 requests per minute
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

# Return 429 Too Many Requests instead of the default 503
limit_req_status 429;

Some details from the official documentation:

  • $binary_remote_addr is preferred over $remote_addr because it stores the address in binary form (4 bytes for IPv4, 16 bytes for IPv6), which saves memory.
  • One megabyte of zone memory holds about 16,000 states of 64 bytes, so 10m is enough for a large number of IP addresses. When the zone is full, Nginx removes the least recently used state; if it still cannot create a new state, the request is rejected with an error.
  • The rate is set in requests per second (r/s) or, for rates below one per second, requests per minute (r/m). For example, 30r/m means one request every two seconds.
  • Without limit_req_status, rejected requests get 503 Service Unavailable. 429 Too Many Requests describes the situation more accurately for clients and monitoring tools.

Step 2: Apply the limits

Apply the zones in your site's server block (for example in /etc/nginx/sites-available/example.com):

server {
    # ... listen, server_name, ssl settings ...

    # General limit for the whole site
    limit_req zone=general burst=20 nodelay;

    # Strict limit for the login page
    location = /login {
        limit_req zone=login burst=5 nodelay;

        # Keep the same proxy_pass or fastcgi lines this URL already uses
        proxy_pass http://127.0.0.1:3000;
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

Important inheritance rule: limit_req directives are inherited from the outer level only if the current level has no limit_req directives of its own. In the example above, location = /login has its own limit_req, so the general limit no longer applies there, only the login limit. If you want both limits, list both in that location. Several limit_req lines are allowed in the same block:

location = /login {
    limit_req zone=general burst=20 nodelay;
    limit_req zone=login burst=5 nodelay;
    proxy_pass http://127.0.0.1:3000;
}

For a PHP site such as WordPress, the login page is a PHP file, so the protected location must also contain your PHP handling (the same include snippets/fastcgi-php.conf; and fastcgi_pass lines your location ~ \.php$ block uses). Otherwise Nginx would serve the file without running it.

What burst, nodelay and delay actually do

This is the part most people get wrong. With rate=10r/s, Nginx allows one request every 100 milliseconds per IP. Real browsers do not behave like that: one page load can request many files at the same moment. The extra options decide what happens to those extra requests.

SettingWhat happens to requests above the rateGood for
limit_req zone=general;Every request that comes too early is rejected immediately. No burst is allowed.Rarely a good idea for pages viewed in a browser.
burst=20Up to 20 extra requests are queued and released at the set rate, so users notice delays. Requests beyond the queue are rejected.Smoothing traffic to a slow backend.
burst=20 nodelayUp to 20 extra requests are served at once without waiting. The burst slots free up again at the set rate. Requests beyond that are rejected.Most websites and APIs. Normal users get fast pages; floods are cut off.
burst=20 delay=8The first 8 extra requests are served at once, the next 12 are delayed, and anything beyond 20 is rejected (two-stage limiting, available since Nginx 1.15.7).Allowing a normal page load quickly while slowing heavier clients.

As a starting point, burst with nodelay is the simplest choice for most sites. Set the burst large enough for one normal page load (count the requests in your browser's developer tools, Network tab) so that real visitors are never affected.

Step 3: Test safely with dry-run mode

Before you enforce limits on a busy site, you can see who would be limited. With limit_req_dry_run on; (available since Nginx 1.17.1), requests are not limited, but they are still counted in the zone and logged:

server {
    limit_req zone=general burst=20 nodelay;
    limit_req_dry_run on;
    # ...
}

Since Nginx 1.17.6 the variable $limit_req_status records the result for each request: PASSED, DELAYED, REJECTED, DELAYED_DRY_RUN or REJECTED_DRY_RUN. Add it to a log format in your http block so you can count the hits:

log_format ratelimit '$remote_addr [$time_local] "$request" $status $limit_req_status';
access_log /var/log/nginx/ratelimit.log ratelimit;

Check your Nginx version with nginx -v. Ubuntu 22.04 and newer, and Debian 11 and newer, ship versions that support both features, but older systems might not.

After a day or two, look for real users who would have been blocked:

grep REJECTED_DRY_RUN /var/log/nginx/ratelimit.log | awk '{print $1}' | sort | uniq -c | sort -rn | head

If you see your own office IP or a monitoring service, raise the burst or allowlist them (see below). When the results look right, remove limit_req_dry_run on;.

Step 4: Check the configuration and reload

Always test the configuration before reloading, so a typo does not take the site down:

sudo nginx -t
sudo systemctl reload nginx

Then send a quick series of requests from a test machine and watch the status codes change to 429:

for i in $(seq 1 15); do
  curl -s -o /dev/null -w "%{http_code}\n" https://example.com/login
done

With rate=5r/m burst=5 nodelay, expect the first six requests to pass (one plus the burst of five) and the rest to return 429. Replace example.com with your own domain, and test only against servers you manage.

Rejected requests are written to the Nginx error log (by default /var/log/nginx/error.log) with the text "limiting requests". You can change their severity with limit_req_log_level, for example limit_req_log_level warn;. Delayed requests are logged one level lower than rejected ones.

Allowlisting trusted IP addresses

The documentation states that requests with an empty key are not counted. You can use this to exclude trusted networks, such as your office or an uptime monitor, by combining the geo and map directives in the http block. The last line below replaces the general zone line from Step 1; a zone name can only be defined once.

geo $limit {
    default        1;
    203.0.113.10   0;   # office IP (example address)
    10.0.0.0/8     0;   # internal network
}

map $limit $limit_key {
    0 "";
    1 $binary_remote_addr;
}

limit_req_zone $limit_key zone=general:10m rate=10r/s;

The example address 203.0.113.10 comes from a range reserved for documentation; replace it with your real address.

Behind Cloudflare, a load balancer or a reverse proxy

If your server sits behind a proxy or CDN, $binary_remote_addr holds the proxy's address, not the visitor's. All visitors then share one bucket, and the limit blocks everyone at the same time. Fix this first with the ngx_http_realip_module, which is included in the Ubuntu and Debian Nginx packages:

set_real_ip_from 192.0.2.0/24;   # your proxy or load balancer range (example)
real_ip_header X-Forwarded-For;
real_ip_recursive on;

Only list proxy addresses you trust. If you trust any source, attackers can forge the header and get around the limit. CDN providers publish their current IP ranges; take them from the provider's official list and keep them up to date. Cloudflare also sends a CF-Connecting-IP header that you can use as the real_ip_header.

Common mistakes

  • No burst on normal pages. A page with 30 images, scripts and stylesheets will trip a 10r/s limit with no burst. Use burst with nodelay, or limit only dynamic URLs.
  • Forgetting the inheritance rule. A limit_req inside a location replaces, rather than adds to, the server-level ones.
  • Limiting static files that a CDN or cache already handles. Focus on expensive or sensitive URLs: login, registration, password reset, search, contact forms and API endpoints.
  • Sharing one zone for very different rates. Each zone has one rate. Create separate zones for "general" and "login" traffic.
  • Treating rate limiting as the whole defence. It slows down brute-force attacks and floods from a single address, but it does not stop large distributed attacks. Combine it with strong passwords or multi-factor authentication, Fail2ban, a firewall and, for large attacks, an upstream DDoS protection service.

Quick checklist

  1. Create zones in the http block with limit_req_zone (separate zones for general and login traffic).
  2. Set limit_req_status 429;.
  3. Apply limit_req with a sensible burst and nodelay.
  4. Fix real client IPs first if you are behind a proxy or CDN.
  5. Run in limit_req_dry_run mode and review the logs.
  6. Run nginx -t, reload, and test with curl.
  7. Allowlist trusted IPs and monitor the error log for "limiting requests".

Sources