0
0
NginxHow-ToBeginner · 4 min read

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 like server or location.

Example parts:

  • $binary_remote_addr: Uses the client's IP address as the key.
  • zone=name:size: Creates a memory zone named name with size for tracking.
  • rate=number[/unit]: Sets the allowed request rate (e.g., 10r/s means 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_zone in the http block causes errors.
  • Setting too low burst can block legitimate traffic spikes.
  • Using nodelay disables 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

DirectivePurposeExample
limit_req_zoneDefines rate limit zone and keylimit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
limit_reqApplies rate limit in server/locationlimit_req zone=one burst=10 nodelay;
burstAllows extra requests to queue temporarilyburst=10
nodelayRejects requests immediately when limit exceedednodelay

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.