On this page
- What can Nginx rate limiting protect against?
- How do I install Nginx and check the version?
- How does limit_req work?
- How do I apply the limits to a site?
- How do I limit parallel connections?
- How do I exempt trusted addresses?
- What if Nginx sits behind a proxy or CDN?
- How do I test limits safely?
- How do I choose good numbers?
- Questions
What can Nginx rate limiting protect against?
It protects your application from too many requests by one client: password guessing on a login form, aggressive scrapers, a buggy script hammering an API, or a small application layer flood. Nginx rejects excess requests cheaply before they reach PHP, Node.js or Python, so the app keeps serving normal visitors.
It cannot stop a flood large enough to fill the network link, because that traffic arrives before Nginx sees it. Filtering at that scale has to happen upstream of the server. Within your VPS, rate limits, a tidy firewall (UFW or firewalld) and an IP ban tool such as fail2ban work well together.
How do I install Nginx and check the version?
Use the distribution package unless you need a newer feature. On Ubuntu and Debian:
sudo apt update
sudo apt install nginx
nginx -vOn Rocky Linux and AlmaLinux, check which module streams are available, then install:
sudo dnf module list nginx
sudo dnf install nginx
sudo systemctl enable --now nginx
nginx -vEvery directive in this guide works on the versions these systems ship today; limit_req_dry_run needs 1.17.1 or later. The full setup, including server blocks, is in the Nginx guide.
How does limit_req work?
It uses a leaky bucket per key. You set an average rate; requests above it wait in a queue up to the burst size, and anything beyond the burst is rejected. Define zones in the http context, for example in a new file that Nginx loads automatically:
sudo nano /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_req_status 429;
limit_req_log_level warn;$binary_remote_addr keys on the client IP in compact form; a 10 MB zone stores state for well over a hundred thousand addresses. rate accepts per second (r/s) or per minute (r/m). The 429 status tells well behaved clients to slow down instead of showing a generic 503.
How do I apply the limits to a site?
Reference the zones inside server or location blocks. A typical site uses a general limit everywhere and a strict one on login and API token endpoints:
server {
listen 80;
server_name example.net;
limit_req zone=perip burst=20 nodelay;
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 /api/ {
limit_req zone=perip burst=40;
proxy_pass http://127.0.0.1:3000;
}
}nodelay serves the burst immediately instead of pacing it, which suits page loads that fetch many files at once. Without it, Nginx spaces queued requests to match the rate, which smooths API traffic. Adjust the PHP socket path to your setup; on Rocky and Alma it is usually /run/php-fpm/www.sock. Check and reload:
sudo nginx -t
sudo systemctl reload nginxHow do I limit parallel connections?
Use limit_conn, which counts open connections per key instead of request rate. It helps against clients that open many slow connections or download large files in parallel:
# http context, in limits.conf
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn_status 429;
# server or location context
limit_conn addr 20;
location /downloads/ {
limit_conn addr 2;
limit_rate 2m;
}limit_rate caps bandwidth per connection, here 2 MB per second. Pair connection limits with short timeouts so idle or slow clients release their slots: client_header_timeout 10s;, client_body_timeout 10s; and keepalive_timeout 15s; in the http block are reasonable starting points.
How do I exempt trusted addresses?
Map trusted networks to an empty key. Nginx does not count requests whose key is empty, so your office, monitoring and internal services pass freely:
geo $limited {
default 1;
203.0.113.0/24 0;
2001:db8:4f2a::/48 0;
}
map $limited $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=perip:10m rate=10r/s;Replace the zone definition from earlier with this version rather than defining perip twice. Uptime checks from Uptime Kuma or a similar tool are a good candidate for the allowlist.
What if Nginx sits behind a proxy or CDN?
Then every request appears to come from the proxy address, and one limit would throttle all visitors together. Restore the real client IP first with the realip module, trusting only the proxy ranges you actually use:
set_real_ip_from 192.0.2.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;After this, $binary_remote_addr holds the visitor address. Never trust forwarded headers from everyone, because any client could fake them and slip past the limits. The Nginx reverse proxy guide shows the matching proxy headers.
How do I test limits safely?
Run in dry run mode first. Nginx then logs what it would reject without blocking anyone:
limit_req_dry_run on;
limit_conn_dry_run on;Generate load from another machine with ApacheBench, packaged as apache2-utils on Ubuntu and Debian and httpd-tools on Rocky and Alma:
ab -n 200 -c 20 https://example.net/
sudo tail -f /var/log/nginx/error.logLook for lines that mention limiting requests and the zone name. When the numbers look right for normal visitors, remove the dry run lines, reload and repeat the test: ab now reports non 2xx responses for the rejected share. A quick check with curl prints the status of each call:
for i in $(seq 1 30); do curl -s -o /dev/null -w "%{http_code} " https://example.net/; doneHow do I choose good numbers?
Measure first. Count how many requests a real page view makes, including images, scripts and API calls, and look at your busiest legitimate clients in the access log:
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | headSet the general rate comfortably above normal use and keep strict limits for login, password reset and signup routes, where people rarely need more than a few tries a minute. Many visitors can share one IP behind mobile carriers and office networks, so avoid very tight general limits. Revisit the numbers after launches or traffic changes, and if you outgrow one server, see Nginx load balancing.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Rate and connection limits in Nginx
Does Nginx rate limiting stop DDoS attacks?
It helps against small application layer floods and abusive clients. Large volumetric floods saturate the network before Nginx sees them; that needs filtering upstream, which a single server cannot provide.
Should I return 429 or 503?
Use 429 Too Many Requests. It describes the situation correctly and many clients back off when they see it.
What does burst do?
It lets a client exceed the average rate briefly. Requests within the burst are queued (or served immediately with nodelay); requests beyond it are rejected.
Can I limit by something other than IP?
Yes. The key can be any variable, such as an API key header or a session cookie, which is useful when many users share one address.
Do limits work for IPv6 clients?
Yes. $binary_remote_addr holds IPv6 addresses too. Since one client can own many IPv6 addresses, keep strict limits on sensitive routes and add fail2ban for repeat offenders.
More in Security
- UFW firewall on Ubuntu and Debian
- firewalld on Rocky Linux and AlmaLinux
- iptables rules that survive a reboot
- Block brute force logins with fail2ban
- CrowdSec intrusion prevention
- Two-factor SSH logins with TOTP
- Disable or restrict root login
- Alerts for every SSH login
- Advanced OpenSSH settings
- Publish SSH host keys in DNS (SSHFP)
- Audit open ports with nmap
- File integrity checks with AIDE and Tripwire
- CSF firewall (ConfigServer Security)
- First security steps on Rocky and Alma
- Free TLS certificates with Certbot
- Self-signed certificates and a private CA
- Wazuh security monitoring
- Kernel and sysctl hardening