How to Rate Limit in Nginx: Simple Guide with Examples
To rate limit in
nginx, use the limit_req_zone directive to define a shared memory zone and request rate, then apply limit_req inside a server or location block to enforce the limit. This setup controls how many requests a client can make per second, helping prevent overload.Syntax
The rate limiting in Nginx uses two main directives:
limit_req_zone: Defines a shared memory zone and key to track clients and sets the request rate limit.limit_req: Applies the rate limit to a specific context likeserverorlocation.
Example parts:
$binary_remote_addr: Uses the client's IP address as the key.zone=name:size: Creates a memory zone namednamewithsizefor tracking.rate=number[/unit]: Sets the allowed request rate (e.g.,10r/smeans 10 requests per second).
nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; server { location / { limit_req zone=mylimit burst=5 nodelay; # other config } }
Example
This example limits each client IP to 5 requests per second with a burst of 10 requests allowed temporarily. Requests beyond this will get a 503 error.
nginx
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
server {
listen 80;
location / {
limit_req zone=one burst=10 nodelay;
return 200 'Request allowed';
}
}
}Output
When a client sends requests faster than 5 per second plus 10 burst, Nginx responds with HTTP 503 Service Temporarily Unavailable.
Common Pitfalls
- Not defining
limit_req_zonein thehttpblock causes errors. - Setting too low
burstcan block legitimate traffic spikes. - Using
nodelaydisables request queuing, causing immediate rejections. - Forgetting to reload Nginx after config changes means limits won't apply.
nginx
Wrong:
server {
location / {
limit_req zone=one burst=5;
}
}
# Missing limit_req_zone definition
Right:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
}
server {
location / {
limit_req zone=one burst=5;
}
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| limit_req_zone | Defines rate limit zone and key | limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s; |
| limit_req | Applies rate limit in server/location | limit_req zone=one burst=10 nodelay; |
| burst | Allows extra requests to queue temporarily | burst=10 |
| nodelay | Rejects requests immediately when limit exceeded | nodelay |
Key Takeaways
Define
limit_req_zone in the http block to set rate limits by client IP.Use
limit_req inside server or location to enforce limits.Adjust
burst to allow short traffic spikes without blocking.Use
nodelay to reject excess requests immediately or omit it to queue them.Always reload Nginx after changing rate limit settings to apply them.