How to Use limit_req_zone in Nginx for Rate Limiting
Use
limit_req_zone in the http block to define a shared memory zone and request rate limit key, then apply limit_req in a server or location block to enforce the limit. This setup helps control how many requests a client can make in a given time, protecting your server from overload.Syntax
The limit_req_zone directive defines a shared memory zone to track request rates and sets the key to identify clients. It is placed in the http block. The main parts are:
$binary_remote_addr: The client IP address used as the key.zone=name:size: Defines the zone name and memory size for tracking.rate=rate: Sets the request rate limit (e.g., 10r/s means 10 requests per second).
nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
Example
This example shows how to limit each client IP to 5 requests per second using a shared memory zone named one. The limit is applied in the location / block.
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;
proxy_pass http://backend;
}
}
}Output
Nginx starts successfully and limits client requests to 5 per second with bursts up to 10 allowed immediately.
Common Pitfalls
Common mistakes when using limit_req_zone include:
- Defining
limit_req_zoneinsideserverorlocationblocks instead ofhttp. - Using an inappropriate key like
$remote_addrwithout considering proxies;$binary_remote_addris more efficient. - Not setting a large enough
zonesize, causing tracking data loss. - Forgetting to apply
limit_reqin theserverorlocationblock after defining the zone.
nginx
http {
# Wrong: limit_req_zone inside server block (incorrect)
server {
limit_req_zone $binary_remote_addr zone=wrongzone:10m rate=1r/s;
}
# Right: limit_req_zone inside http block
limit_req_zone $binary_remote_addr zone=correctzone:10m rate=1r/s;
server {
limit_req zone=correctzone burst=5;
}
}Quick Reference
| Directive | Description | Example |
|---|---|---|
| limit_req_zone | Defines shared memory zone and rate limit key | limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s; |
| limit_req | Applies the rate limit in server/location block | limit_req zone=one burst=10 nodelay; |
| $binary_remote_addr | Client IP address in binary form (efficient key) | Used as key in limit_req_zone |
| zone | Name and size of shared memory zone | zone=one:10m |
| rate | Request rate limit (requests per second) | rate=5r/s |
| burst | Allows bursts of requests exceeding rate temporarily | burst=10 |
| nodelay | Processes burst requests immediately without delay | nodelay |
Key Takeaways
Define limit_req_zone in the http block with a key and rate limit.
Apply limit_req in server or location blocks to enforce the limit.
Use $binary_remote_addr as the key for efficient client identification.
Set an appropriate zone size to store request states.
Use burst and nodelay to control request bursts smoothly.