Implement Rate Limiting in Nginx
Intermediatev1.0.0
Configure Nginx rate limiting — per-IP request limits, burst handling, zone configuration, and different limits for API endpoints vs static content.
Content
Overview
Nginx rate limiting controls how many requests a client can make in a given time window. It protects against brute-force attacks, DDoS, and API abuse by limiting requests per IP address or other identifiers.
Why This Matters
- -DDoS protection — limits request flood impact
- -Brute-force prevention — slows credential stuffing attacks
- -API abuse prevention — enforces fair usage limits
- -Resource protection — prevents server overload
How It Works
Step 1: Define Rate Limit Zones
Step 2: Apply Rate Limits
Step 3: Connection Limiting
Step 4: Custom Error Page
Rate Limit Parameters
| Parameter | Effect |
|---|---|
| `rate=10r/s` | 10 requests per second sustained rate |
| `burst=20` | Allow 20 excess requests to queue |
| `nodelay` | Process burst immediately (no queuing) |
| `delay=10` | Process first 10 burst requests immediately, queue rest |
Best Practices
- -Use different zones for different endpoint types
- -Set burst to handle legitimate traffic spikes
- -Use nodelay for API endpoints (reject excess, don't queue)
- -Use delay for web pages (queue briefly for better UX)
- -Return 429 status code (standard for rate limiting)
- -Log rate limit events for monitoring
- -Exempt known-good IPs (load balancers, monitoring)
Common Mistakes
- -No burst setting (rejects legitimate bursty traffic)
- -Same rate limit for login and static assets
- -Not returning 429 status (clients cannot distinguish rate limit from errors)
- -Rate limiting internal health check endpoints
- -Not logging rate limit events (invisible abuse attempts)
FAQ
Discussion
Loading comments...