Search code examples
nginxnginx-locationnginx-configrate-limiting

Nginx Rate limit GET or POST requests only at a location


I have a server in nginx configured and have the following code to create my rate limit zone:

limit_req_zone $key zone=six_zone:10m rate=60r/m;

In my location, I use a module to serve the requests. This location supports GET, POST and DELETE methods. I am trying to rate limit only GET requests to that location. This is what I thought might work but it does not.

location /api/ {
    if ($request_method = GET) {
        limit_req zone=six_zone;
    }
    reqfwder;
}

Any help or pointers towards how I can approach this? Thanks.


Solution

  • Hope this helps,

    In the http context of your NGINX configuration, add these lines:

    http {
      ... # your nginx.conf here
      
      # Maps ip address to $limit variable if request is of type POST
      map $request_method $limit {
        default         "";
        POST            $binary_remote_addr;
      }
      
      # Creates 10mb zone in memory for storing binary ips
      limit_req_zone $limit zone=my_zone:10m rate=1r/s;
    }
    
    **Rate limiting for the entire NGINX process:**
    http {
        ... # your nginx.conf here
        limit_req zone=global_zone;
    }
    

    REF: https://product.reverb.com/first-line-of-defense-blocking-bad-post-requests-using-nginx-rate-limiting-507f4c6eed7b