How to install rate-limit nginx templates

User avatar
myVesta
Site Admin
Posts: 918
Joined: Fri Jun 19, 2020 9:59 am
Has thanked: 8 times
Been thanked: 6 times

Solution for different rate-limit for different IP addresses and optionally different folders:

/etc/nginx/nginx.conf part should look like this:

Code: Select all

    geo $limited_ip {
        default           0;
        123.123.123.123/24   1;
        234.234.234.234/24   2;
    }

    map $limited_ip $limited_ip_key0 {
        0 $binary_remote_addr;
        1 '';
        2 '';
    }
    map $limited_ip $limited_ip_key1 {
        0 '';
        1 $binary_remote_addr;
        2 '';
    }
    map $limited_ip $limited_ip_key2 {
        0 '';
        1 '';
        2 $binary_remote_addr;
    }

    limit_conn_zone $limited_ip_key0 zone=zone0_addr:1m;
    limit_conn_zone $limited_ip_key1 zone=zone1_addr:1m;
    limit_conn_zone $limited_ip_key2 zone=zone2_addr:1m;
    limit_req_zone $limited_ip_key0 zone=zone0:1m rate=2r/s;
    limit_req_zone $limited_ip_key1 zone=zone1:1m rate=20r/s;
    limit_req_zone $limited_ip_key2 zone=zone2:1m rate=20r/s;

    limit_conn_zone $binary_remote_addr zone=addr:1m;
    limit_req_zone $binary_remote_addr zone=one:1m rate=1r/s;
    limit_req_zone $binary_remote_addr zone=two:1m rate=2r/s;
    limit_conn_log_level error;
    limit_req_log_level error;
    limit_conn_status 429;
    limit_req_status 429;
Template part:

Code: Select all

    location / {
        limit_conn zone0_addr 8;
        limit_conn zone1_addr 24;
        limit_conn zone2_addr 24;
        limit_req zone=zone0 burst=14 delay=7;
        limit_req zone=zone1 burst=140 delay=70;
        limit_req zone=zone2 burst=140 delay=70;
        proxy_pass      https://%ip%:%web_ssl_port%;
    }
    location /wp-admin/ {
        limit_conn zone0_addr 24;
        limit_req zone=zone0 burst=140 delay=70;
        proxy_pass      https://%ip%:%web_ssl_port%;
    }

Tags:
Post Reply