How to Implement Rate Limiting on NGINX

Implementing rate limiting on NGINX is a great way to prevent abuse, denial-of-service (DoS) attacks, or excessive usage of your server resources. Here’s a step-by-step guide on how to do it:

Step 1: Install the ngx_http_limit_req_module

The ngx_http_limit_req_module is required for rate limiting in NGINX. You can install it using the following command:

sudo apt-get install nginx-extras

This module provides a simple and effective way to limit a client’s number of requests within a given time period.

Step 2: Configure Rate Limiting

In your NGINX configuration file (usually nginx.conf or default.conf), add the following block:

http {
    ...
    server {
        listen 80;
        server_name example.com;

        location / {
            limit_req zone=one;
        }
    }
}

The limit_req directive sets a rate limit for the specified location. In this case, we’re setting a limit of one request per second (1req/s) with a burst size of 10 (i.e., up to 10 requests can be made within a single second before the limit kicks in).

Step 3: Define the zone

The zone parameter defines the rate-limiting zone. You can create multiple zones and assign them different rates or burst sizes.

http {
    ...
    server {
        listen 80;
        server_name example.com;

        http {
            limit_req_zone $binary_remote_addr/32 10m;
        }
    }
}

In this example, we’re creating a rate-limiting zone for the $binary_remote_addr variable (i.e., the client’s IP address) with a size of 10 megabytes.

Step 4: Restart NGINX *
Restart your NGINX service to apply the changes:

sudo service nginx restart

Now, if clients make more than one request per second, they will be rate-limited and receive a 503 Service Unavailable response.
Tips and Variations:

  • You can adjust the rate limit and burst size to suit your specific needs.
  • Use the limit_req_status directive to specify the status code returned when the rate limit is exceeded (e.g., 503, 429, or any other status code).
  • Implement additional security measures, such as IP blocking or CAPTCHA challenges, for clients that exceed the rate limit.

By implementing rate limiting on NGINX, you can protect your server from abuse and ensure a more stable and secure online experience for your users.

Recent Articles

Related Stories

Stay on op - Ge the daily news in your inbox