0

Because limit_req_zone must be specified in HTTP context and cannot be in server or even in location context, it seems one can only set a rate limit for the entire server.

Nginx is used to serve static files and one may do this as often as they like. However, the /api/... path is proxied to the application server and should not be hit with a DoS attack. How can I configure Nginx to only rate limit the API?

Luc
  • 294
  • 3
  • 18

1 Answers1

2

The first argument to limit_req_zone is a key to keep a state for. The documentation tells us:

Requests with an empty key value are not accounted.

To only rate limit certain parts of the site, we need to make those parts have a non-empty key. We can do this by mapping the /api/... URI space to the remote IP address and mapping everything else to an empty key:

http {
    [the rest of your configuration]

    map $uri $apicall {
        default "";
        ~api $binary_remote_addr;
    }
    limit_req_zone $apicall zone=mylimit:100m rate=10r/s;
}

Note that we use $binary_remote_addr as explained in their rate limiting blog post.

Luc
  • 294
  • 3
  • 18