NewCode CLOUD — 20% off your first month on all cloud VPSClaim

Nginx Rate Limiting: Protect Logins, APIs and Sites from Floods and Scrapers

A single bot hammering wp-login.php, a scraper downloading your whole catalogue, or a small HTTP flood can make a site slow for everyone else. Nginx has rate limiting built in: it can cap how many requests per second each client may make and how many connections it may hold open. Configured well, real visitors never notice it and abusive clients are slowed or rejected before they reach PHP, Node.js or your database.

Two modules

Module Limits Typical use
limit_req Requests per time unit Logins, APIs, search, the whole site
limit_conn Concurrent connections Downloads, slow clients, connection floods

Both are compiled into standard Nginx packages.

Basic request limiting

Define a zone in the http block (for example in /etc/nginx/conf.d/limits.conf):

# 10 MB of memory holds about 160,000 IP addresses
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_status 429;

Then apply it in a server or location block:

server {
    # General limit for the whole site
    limit_req zone=perip burst=40 nodelay;

    location = /wp-login.php {
        limit_req zone=login burst=3 nodelay;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
}

Test and reload:

sudo nginx -t && sudo systemctl reload nginx

Understanding rate, burst and nodelay

This is where most configurations go wrong.

  • rate=10r/s — the long-term average allowed: one request every 100 ms. Nginx tracks this per key with millisecond precision; it does not mean “10 requests in any second”.
  • burst=40 — how many requests above the rate can queue up. Browsers load a page’s HTML, CSS, JS and images in a quick burst; without a burst value, the second request within 100 ms would be rejected.
  • nodelay — serve queued burst requests immediately instead of spacing them out at the rate. Without it, a burst of 20 requests would trickle out over 2 seconds, making pages feel slow.

So rate=10r/s burst=40 nodelay means: a client can fire up to 40 requests at once (a page load), and then sustain 10 per second. Requests beyond that get 429 Too Many Requests.

Scenario Recommended
Whole site, normal pages rate=10r/s burst=40–100 nodelay
Login / password reset rate=5r/m burst=3–5 nodelay
Search, expensive endpoints rate=1r/s burst=5 nodelay
Public API Based on your API’s documented limits

Static files (images, CSS) do not need limits if they are served directly by Nginx; you can put the general limit only on dynamic locations (location ~ \.php$ or the proxy location).

Limiting connections

limit_conn_zone $binary_remote_addr zone=connperip:10m;

server {
    limit_conn connperip 20;
    limit_conn_status 429;

    location /downloads/ {
        limit_conn connperip 2;      # two parallel downloads per IP
        limit_rate 5m;               # 5 MB/s per connection
    }
}

limit_rate caps bandwidth per connection, which keeps one downloader from saturating your port.

Behind Cloudflare or another proxy: use the real IP

If your site sits behind Cloudflare or a load balancer, $binary_remote_addr is the proxy’s IP — every visitor shares the same limit, and you will block everyone. Restore the visitor’s IP first with the realip module:

# /etc/nginx/conf.d/cloudflare-realip.conf
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
# ...the full, current list published by Cloudflare...
real_ip_header CF-Connecting-IP;

Cloudflare publishes its IP ranges at https://www.cloudflare.com/ips/; keep the list up to date. Full setup in Cloudflare with your origin server.

Only trust these headers from the proxy’s addresses. Accepting X-Forwarded-For from anyone lets attackers choose their own “IP”.

Whitelisting your own systems

Monitoring, your office and internal services should not be limited. Use a geo + map pair to give them an empty key (empty keys are not limited):

geo $limit {
    default        1;
    127.0.0.1      0;
    198.51.100.7   0;     # office
    10.10.0.0/24   0;     # private network
}
map $limit $limit_key {
    0 "";
    1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=perip:10m rate=10r/s;

Dry run before enforcing

Nginx 1.17.1+ can log what would be limited without blocking anything:

limit_req_dry_run on;

Watch the error log for “limiting requests, dry run” messages during normal traffic, adjust rates, then remove the directive.

Logging and monitoring

Rejected requests appear in the error log:

limiting requests, excess: 40.520 by zone "perip", client: 203.0.113.66

Count 429 responses in the access log:

awk '$9 == 429 {print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head

Clients that collect many 429s are good candidates for a longer ban with Fail2ban, using a filter that matches status 429.

Friendly error page

Return a short page instead of Nginx’s default:

error_page 429 /429.html;
location = /429.html {
    root /var/www/errors;
    internal;
}

For APIs, return JSON and a Retry-After header so well-behaved clients back off.

What rate limiting cannot do

Rate limiting works per IP address on traffic that reaches your server. It cannot help when:

  • An attack saturates your bandwidth — the traffic never gets as far as Nginx. That needs network-level protection such as high-defence IPs; see DDoS protected hosting.
  • An attack comes from tens of thousands of IPs, each sending only a few requests. Here caching (so each request is cheap), a CDN/WAF, or challenge pages help more.

Combine layers: a firewall that exposes only ports 80/443, Nginx rate limits, caching for anonymous pages, Fail2ban for repeat offenders, and upstream DDoS protection for volumetric attacks.

Complete example

# /etc/nginx/conf.d/limits.conf
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_conn_zone $binary_remote_addr zone=connperip:10m;
limit_req_status 429;
limit_conn_status 429;

# in your server block
limit_conn connperip 30;
location ~ \.php$ {
    limit_req zone=perip burst=40 nodelay;
    # ...fastcgi settings...
}
location = /wp-login.php {
    limit_req zone=login burst=5 nodelay;
    # ...fastcgi settings...
}