Score:1

Rate limit config not working in nginx

mx flag

I'm trying to rate limit any calls to URLs with prefix /api/, I've configured a rate limit with the configuration attached, but I'm not seeing any throttling when using Axios to test.

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
server {
    server_name gmmff.test;
    root /home/angel/wdev/laravel/gmf/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    error_log /var/log/nginx/gmf.log warn;
    access_log /var/log/nginx/gmf-access.log;
    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location /api/ {
        limit_req zone=mylimit;
        rewrite ^/api/(.*)$ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

}
Score:0
jp flag

The URIs beginning with /api/ are rewritten to /index.php and the limit_req directive is no longer in scope when the latter URI is being processed.

Option 1) You could process the index.php file within the location /api/ block.

For example:

location /api/ {
    limit_req zone=mylimit;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root/index.php;
    fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
}

Simply point SCRIPT_FILENAME to the location of index.php.


Option 2) Move the limit_req directive so that it is always in scope, but effectively turn it on and off by manipulating the "key" variable with a map directive.

For example:

map $request_uri $token {
    ~^/api/    $binary_remote_addr;
    default    '';
}
limit_req_zone $token zone=mylimit:10m rate=1r/s;

server {
    ...
    limit_req zone=mylimit;
    ...
}

From the documentation:

Requests with an empty key value are not accounted.

Angel avatar
mx flag
I've tried method number 1, with the following config https://pastebin.com/fC5EBifi I set the rate to 3r/s but the end result was it rate limiting at 1r/s, I tried method 2 and the same result.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.