Nginx Config by Example: Rate Limiting
Protecting against abuse with request throttling through this sample code demonstrating limit_req_zone for defining rate limit zones, limit_req for applying limits, burst parameter for traffic spikes, and IP-based request tracking.
Code
http {
# Define a limit zone
# $binary_remote_addr: key (client IP)
# zone=mylimit:10m: name and size of shared memory zone
# rate=10r/s: maximum request rate
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
listen 80;
location /login {
# Apply the limit
# burst=5: allow a burst of 5 requests
# nodelay: don't delay excessive requests, reject them immediately
limit_req zone=mylimit burst=5 nodelay;
proxy_pass http://auth_service;
}
location / {
# No limit here
try_files $uri $uri/ =404;
}
}
}Explanation
Rate limiting restricts the number of requests a client can make within a given time period, protecting servers from brute-force attacks on login pages and DDoS attacks. Nginx implements rate limiting through a two-step process: defining a limit zone in the http block with limit_req_zone, and applying it in specific locations with limit_req. The limit zone stores request counters in shared memory accessible across all worker processes.
The limit_req_zone directive requires three parameters: a key for tracking (typically $binary_remote_addr for client IP addresses), a named shared memory zone with size specification, and a rate limit expressed as requests per second or minute. The $binary_remote_addr variable uses a binary representation of IP addresses, consuming less memory than the string $remote_addr variable. A 10MB zone can track approximately 160,000 IP addresses.
The limit_req directive applies the zone to specific locations with optional burst and nodelay parameters. The burst parameter allows clients to briefly exceed the rate limit to accommodate natural traffic spikes, queuing excess requests up to the burst size. The nodelay parameter processes burst requests immediately rather than delaying them, but requests exceeding burst plus rate are rejected with 503 Service Unavailable errors. Without nodelay, excess requests are delayed to smooth traffic to the specified rate.
Code Breakdown
limit_req_zone must be in http block, defines shared memory zone.$binary_remote_addr uses binary IP representation for memory efficiency.burst=5 allows temporary traffic spikes above baseline rate.nodelay processes burst requests immediately, rejects excess with 503.
