Implementing advanced rate limiting in Nginx using limit_req
Use Nginx limit_req_zone and limit_req to cap requests per second, allow bursts, key limits by IP or API token and return clean 429 responses instead of letting abuse through.
- Intermediate
- Linux VPS
- 6 min read
Nginx rate limiting with limit_req caps how many requests a single client can make in a given time window, so one IP or API key cannot flood your application. This guide builds a full setup: shared memory zones, burst and delay tuning, a clean 429 response with Retry-After, and a dry run you can watch in the logs before you enforce anything.
Before you start
You need:
- A Linux VPS with Nginx installed and serving a site or reverse proxy. If Nginx is not set up yet, follow Install Nginx and host your first website.
- Root or
sudoaccess to edit files under/etc/nginx/. - A test endpoint you can hit repeatedly, for example
https://example.com/api/health. - Optional:
apache2-utils(forab) orheyto generate load.
Rate limits apply to real users as well as attackers. Always test with limit_req_dry_run on first, and never apply a tight limit to a whole server block before you know what normal traffic looks like.
How Nginx rate limiting works
Two directives do the work:
limit_req_zonedefines a shared memory zone, a key and a rate. It lives in thehttpcontext only.limit_reqapplies a zone to aserverorlocationblock and decides what happens when the rate is exceeded.
The key is usually $binary_remote_addr, the compact binary form of the client IP. Requests that arrive faster than the configured rate are delayed if burst allows it, and rejected once the burst queue is full. The zone is shared across all worker processes, so the limit is global, not per worker.
A rate of 10r/s means one request every 100 milliseconds. You can also write rates per minute, such as 30r/m.
Step 1: Define rate limit zones
Create a file that Nginx includes inside the http block. On Debian and Ubuntu that is /etc/nginx/conf.d/ratelimit.conf; on AlmaLinux and Rocky it is /etc/nginx/conf.d/ratelimit.conf as well.
# /etc/nginx/conf.d/ratelimit.conf
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $server_name zone=perserver:10m rate=100r/s;
limit_req_status 429;
limit_req_log_level warn;Notes on the values:
periplimits each client IP.perserverlimits the total across a virtual host, which protects a backend from a distributed flood.10mof memory holds roughly 16,000 client states, so it covers a large number of distinct IPs.limit_req_status 429changes the default rejection code from503to429 Too Many Requests, which is the correct signal for clients and API consumers.
Step 2: Apply limits to a location
Add limit_req inside the location you want to protect. A reverse proxy for an API is the typical case.
server {
listen 443 ssl;
server_name example.com;
location /api/ {
limit_req zone=perip burst=20 nodelay;
limit_req zone=perserver burst=200;
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}Both zones are checked. A request must pass the per-IP limit and the per-server limit.
Step 3: Tune burst, nodelay and delay
burst is the number of excess requests Nginx will hold in a queue for a client that is over the rate. Without burst, any request above the rate is rejected immediately.
burst=20 nodelay— the client may make 20 extra requests instantly, then everything above that is rejected. Good for APIs and page loads with parallel asset requests.burst=20(nonodelay) — extra requests are queued and released at the configured rate. This smooths traffic but adds latency.burst=20 delay=10— the first 10 excess requests are served immediately, the rest are delayed. Useful when you want a small instant allowance plus smoothing.
For a login or password reset endpoint, a small burst with no nodelay is usually the right choice:
location = /api/login {
limit_req zone=perip burst=5;
proxy_pass http://127.0.0.1:3000;
}Step 4: Return a clean 429 response
The default Nginx error page is plain HTML. API clients expect JSON and a Retry-After header.
location /api/ {
limit_req zone=perip burst=20 nodelay;
limit_req_status 429;
error_page 429 = @too_many;
proxy_pass http://127.0.0.1:3000;
}
location @too_many {
default_type application/json;
add_header Retry-After 1 always;
return 429 '{"error":"rate_limited","retry_after":1}';
}Set Retry-After to a value that matches your rate. If the zone allows 10r/s, one second is a reasonable hint.
Step 5: Test in dry run mode
Before enforcing, run the zone in dry run mode so Nginx logs what it would reject without rejecting it.
limit_req_dry_run on;
limit_req_log_level notice;Reload and watch the error log:
sudo nginx -t && sudo systemctl reload nginx
sudo tail -f /var/log/nginx/error.logYou will see lines such as:
2026/01/01 12:00:00 [error] 1234#1234: *56 limiting requests, excess: 1.000 by zone "perip", client: 203.0.113.10, server: example.com, request: "GET /api/health HTTP/1.1"If the log stays quiet during normal traffic, turn dry run off and reload again.
Step 6: Whitelist IPs and key by API token
An empty key means "do not limit this request", which is the cleanest way to exempt monitoring, office IPs or your own load balancer.
geo $limit_key {
default $binary_remote_addr;
203.0.113.10 "";
10.0.0.0/8 "";
}
limit_req_zone $limit_key zone=perip:10m rate=10r/s;To enforce per-customer quotas instead of per-IP, key on the API token. Fall back to the IP when no token is sent.
map $http_authorization $quota_key {
default $http_authorization;
"" $binary_remote_addr;
}
limit_req_zone $quota_key zone=perkey:10m rate=30r/s;Long keys use more zone memory than a 4-byte IP, so size the zone generously if you key on headers.
Check it works
Send a burst of requests and count the status codes:
for i in $(seq 1 40); do
curl -s -o /dev/null -w "%{http_code} " https://example.com/api/health
done; echoYou should see a run of 200 responses followed by 429 once the burst is used up. With ab installed, a heavier test looks like this:
sudo apt install -y apache2-utils
ab -n 300 -c 25 https://example.com/api/healthIn the ab summary, check "Non-2xx responses". Then confirm the rejections in the log:
sudo grep "limiting requests" /var/log/nginx/error.log | tail -n 5Troubleshooting
- Every user gets 429 behind a CDN or load balancer. The key is the proxy IP, not the visitor. Configure the real IP module with
set_real_ip_fromandreal_ip_header X-Forwarded-For, or key the zone on$http_x_forwarded_for. - Normal page loads are rejected. Static assets share the same zone as the API. Give assets their own location with a looser limit, or exclude them from the limited block entirely.
- Requests are rejected but nothing appears in the log.
limit_req_log_levelis set too high, orlimit_req_dry_runis still on. Set the level tonoticewhile testing. - `limit_req directive is not allowed here`. You placed
limit_reqinside anifblock or in a context that does not accept it. Move it into aserverorlocationblock. - `zone "perip" is exhausted` in the log. The shared memory is full and Nginx is evicting old entries. Increase the zone size, for example from
10mto50m. - Limits apply to the wrong site. A
limit_req_zoneis global, butlimit_reqis per location. Check that the zone name in the location matches the one you defined.
Next steps
- Review the simpler starting point in Rate limit requests in Nginx with limit_req.
- Block known bad networks outright with Allow or block IP addresses in Nginx.
- Add automatic bans for repeat offenders in Protect Nginx with Fail2ban: bad bots, scanners and auth.
- Learn to read rejection patterns in Read and manage Nginx access and error logs.
- Need a server to run this on? Compare Linux VPS plans.
Was this guide helpful?
Still stuck?
Ask RunRacks AI for a quick answer, or open a ticket and our team will take a look at your server.
Related guides
Control panels
How to install Plesk on a Linux VPS (AlmaLinux and Ubuntu)
Install Plesk on a fresh Linux VPS with the official one-click installer, apply your licence key and log in to the panel for the first time on port 8443.
- Beginner
- Linux VPS
- 8 min read
Control panels
CyberPanel: back up and restore a website
Create on-demand and scheduled website backups in CyberPanel, download the archives off the server, and restore a site from a backup when something breaks.
- Intermediate
- Linux VPS
- 6 min read
Control panels
Plesk Backup Manager: schedule backups and restore a site
Set up scheduled backups in Plesk Backup Manager, keep a copy off the server, and restore a single domain or subscription when something goes wrong.
- Intermediate
- Linux VPS
- 7 min read