How to Fix Nginx Rate Limiting Configuration Error
In this tutorial, you'll learn about How to Fix Nginx Rate Limiting Configuration Error. We cover key concepts, practical examples, and best practices.
Nginx rate limiting is not working — requests are not being limited even though limit_req_zone is configured, or legitimate requests are being rate-limited when they should not be.
The Problem
# Wrong: Zone defined but never referenced
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
# No limit_req directive here - rate limiting not applied
location /api/ {
proxy_pass http://backend:3000;
}
}
Step-by-Step Fix
Step 1: Define zone and apply it
http {
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend:3000;
}
}
}
Step 2: Log rate limiting events
limit_req_log_level notice;
limit_req_status 429;
Step 3: Whitelist certain IPs
geo $limit {
default 1;
10.0.0.0/8 0;
192.168.0.0/16 0;
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=whitelist:10m rate=10r/s;
Step 4: Test rate limiting
for i in $(seq 1 15); do
curl -s -o /dev/null -w "%{http_code}\n" http://localhost/api/test
done
Expected: first 10 requests return 200, requests 11+ return 429.
Prevention Tips
- Combine
burstwithnodelayfor optimal user experience - Log rate limiting events to debug over-limiting
- Use
$binary_remote_addrfor IP-based limiting - Set different rate limits for different endpoints
Common Mistakes with rate limit
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro