Rate Limiting on Nginx

To limit by remote IP with a single global rate:

limit_req_zone $binary_remote_addr zone=your_zone:10m rate=5r/s;
server {
    ...
    limit_req zone=your_zone burst=5;
    ...
}

To limit by remote IP with a single global rate, but customise for a specific path:

limit_req_zone $binary_remote_addr zone=your_zone:10m rate=5r/s;
server {
    ...
    limit_req zone=your_zone burst=5;
    location /path/ {
        limit_req zone=your_zone burst=10;
    }
    ...
}

To limit by remote IP with multiple rate settings:

limit_req_zone $binary_remote_addr zone=your_zone_1:10m rate=5r/s;
limit_req_zone $binary_remote_addr zone=your_zone_2:25m rate=10r/s;
server {
    ...
    limit_req zone=your_zone_1 burst=5;
    location /path/ {
        limit_req zone=your_zone_2 burst=10;
    }
    ...
}

To limit by server name:

limit_req_zone $server_name zone=your_zone:10m rate=10r/s;
server {
    ...
    limit_req zone=your_zone burst=5;
    ...
}

The actual value for size and rate should be carefully calculated and tuned base on your need.


AI Summary
Chrome On-device AI 2024-10-04 22:47:46

Share Article