How to rate-limit using nginx in linux?

Nginx Settings to rate-limit 5 req/sec

If you want to implement rate limiting on nginx server you can use following settings accroding to your need:

  • limit_req_zone: define this setting under http block so that it can be used with multiple context
  • $binary_remote_addr: is basically user or client IP address
  • zone: defines zone that is used to store each ip address state
  • rate: defines rate limit that you want to use to add throttling

Two-stage rate limiting in nginx

Following code allows 5 req/sec. The configuration allows bursts of up to 12 requests, the first 8 of which are processed without delay. A delay is added after 8 excessive requests to enforce the 5 r/s limit. After 12 excessive requests, any further requests are rejected.

limit_req_zone $binary_remote_addr zone=ip:10m rate=5r/s;

server {
    listen 80;
    location / {
        limit_req zone=ip burst=12 delay=8;
        
        proxy_pass http://backend-server;
    }
}

Source: Nginx.Com