How to set up rate limiting in nginx?
Published on Aug. 22, 2023, 12:19 p.m.
To set up rate limiting in NGINX, you need to configure the ngx_http_limit_req_module
module. Here are the basic steps:
- First, you need to define a shared memory zone in the NGINX configuration file to store the state of the rate limiting. For example, you can add the following code in the
http
block of your configuration file:
http {
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=30r/m;
}
This defines a shared memory zone called “mylimit” that allows a maximum of 30 requests per minute per IP address.
- Next, you need to define the actual rate limiting. You can do this by adding the following code to the location block of your configuration file where you want to apply rate limiting:
location /api/ {
limit_req zone=mylimit;
# Your other configuration directives for this location block
}
This code applies rate limiting using the shared memory zone called “mylimit”.
You can customize the rate limiting parameters and adjust the rate and units (requests per second, minute or hour) according to your requirements.
That’s it! With these configurations in place, NGINX will now enforce the rate limiting rules for the specified location.
Note that the limit_req_zone
directive should be inside the http block and the limit_req
directive should be inside the location block.