Security
Rate Limiting with Nginx: Protect Logins, APIs and Your Server
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيEvery public server receives traffic it did not ask for: bots guessing passwords on login pages, scrapers pulling thousands of pages a minute, and buggy clients retrying in tight loops. Even without bad intent, a single client sending too many requests can exhaust PHP workers or database connections and slow the site for everyone. Rate limiting puts a ceiling on how fast each client can make requests. Nginx has this built in, and with a few lines of configuration you can protect login forms, APIs and expensive endpoints. This guide walks through the directives, sensible values and how to roll limits out without blocking real users.
How Nginx rate limiting works
Nginx uses the leaky bucket algorithm. Each client, usually identified by IP address, has a bucket that drains at a fixed rate. Requests that arrive within the rate are processed. Requests that arrive faster fill the bucket. If the bucket has room (the burst), extra requests wait or pass immediately depending on your settings. When the bucket is full, Nginx rejects the request.
Two modules handle limits:
| Module | Limits | Typical use |
|---|---|---|
ngx_http_limit_req_module | Requests per second or minute | Logins, APIs, search, form submissions |
ngx_http_limit_conn_module | Concurrent connections | Downloads, long-running requests, slow clients |
Both are included in standard Nginx builds.
Step 1: Define a zone
Zones are defined in the http block, typically in /etc/nginx/nginx.conf or a file under /etc/nginx/conf.d/:
http {
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_conn_zone $binary_remote_addr zone=perip:10m;
}$binary_remote_addris the client IP in compact binary form, which saves memory compared to$remote_addr.zone=login:10mcreates a shared memory area namedloginof 10 MB. According to the Nginx documentation, one megabyte holds roughly 16,000 states, so 10 MB is plenty for most sites.rate=5r/mmeans five requests per minute. Rates can be per second (r/s) or per minute (r/m).
Step 2: Apply limits to locations
server {
listen 443 ssl;
server_name example.com;
limit_req_status 429;
limit_conn_status 429;
location / {
limit_req zone=general burst=20 nodelay;
try_files $uri $uri/ /index.php?$args;
}
location = /wp-login.php {
limit_req zone=login burst=3 nodelay;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
location /downloads/ {
limit_conn perip 2;
}
}Adjust the PHP socket path to the version installed on your server. Then test and reload:
sudo nginx -t && sudo systemctl reload nginxUnderstanding burst and nodelay
These two options decide how the limit feels to real users.
- No burst: any request faster than the rate is rejected immediately. This is too strict for normal browsing, because one page load can trigger many requests at once.
- burst=20: up to 20 extra requests are queued and released at the defined rate. Users see a delay instead of an error.
- burst=20 nodelay: the 20 extra requests are served immediately, but the slots refill only at the defined rate. This is usually the best choice for websites: short spikes feel fast, sustained floods are rejected.
There is also delay=N (available since Nginx 1.15.7), which serves the first N excess requests immediately and delays the rest.
Return 429, not 503
By default Nginx answers rejected requests with 503 Service Unavailable, which monitoring tools and search engines interpret as an outage. The limit_req_status 429 and limit_conn_status 429 lines above return 429 Too Many Requests instead, which correctly tells clients to slow down.
Exempting trusted addresses
Your own office, monitoring service or internal health checks should not be limited. Combine geo and map so that trusted IPs get an empty key, and Nginx does not count requests with an empty key:
geo $limited {
default 1;
203.0.113.10 0;
10.0.0.0/8 0;
}
map $limited $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=api:10m rate=20r/s;Behind a proxy or CDN
If your server sits behind a reverse proxy or CDN, every request appears to come from the proxy's IP, and one limit would apply to all visitors together. Use the real IP module to restore the client address from a trusted header, and list only the proxy's own address ranges:
set_real_ip_from 192.0.2.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;Never trust that header from arbitrary sources, or attackers can forge it to bypass limits.
Roll out safely with dry run
Since Nginx 1.17.1 you can test limits without enforcing them:
limit_req zone=general burst=20 nodelay;
limit_req_dry_run on;Requests that would have been rejected are logged but still served. Watch the error log with sudo tail -f /var/log/nginx/error.log, look for "limiting requests" entries, and adjust rates before turning dry run off. You can generate test load from another machine with a tool such as ab -n 200 -c 20 https://example.com/.
Practical starting values
| Endpoint | Suggested starting point |
|---|---|
| Whole site | 10r/s, burst=20 nodelay |
| Login and password reset | 5r/m, burst=3 nodelay |
| Public API | 10 to 30r/s per client, depending on your clients |
| Search and heavy reports | 1 to 2r/s, burst=5 |
| Large downloads | limit_conn 2 per IP |
These are starting points, not rules. Check your access logs to see how fast real users actually make requests.
Rate limiting works best alongside other layers. A web application firewall filters malicious payloads that arrive slowly, and fail2ban can ban IPs that keep hitting limits. When your traffic grows beyond what limits can smooth out, check our VPS plans for more CPU and RAM.
FAQ
Can rate limiting stop a DDoS attack?
It helps against small floods from a limited number of IPs and against application-level abuse. It cannot stop a large distributed attack that saturates your network connection, because the traffic arrives before Nginx can reject it. That needs filtering upstream of the server.
Will rate limiting affect users behind the same IP?
Yes. Offices, universities and mobile carriers often place many people behind one shared address. Set limits with a generous burst, focus strict limits on sensitive endpoints such as logins, and monitor 429 responses in your logs after rollout.
What is the difference between limit_req and limit_conn?
limit_req controls how many requests a client can make over time. limit_conn controls how many connections a client can hold open at the same moment. Use limit_req for logins and APIs and limit_conn for downloads or long-lived requests.