limit download speed in nginx

How to Limit Download Speed in NGINX

It is important to limit HTTP bandwidth on your website to prevent a few users from cornering all your downloads and ensure that all users have good user experience. In this article, we will look at how to limit download speed in NGINX, which in turn limits HTTP bandwidth. As a result, each user will be able to download content at a maximum download speed that we define.


How to Limit Download Speed in NGINX

Here is how to limit download speed in NGINX. We will use limit_rate directive to limit download speed in NGINX. We have assumed that you have already installed NGINX on your server. Here are the steps to install NGINX.


1. Limit HTTP bandwidth

limit_rate directive allows you to limit download speed in NGINX. You can add it in http, location or server blocks

Here’s an example to limit download speed to 50kb/sec.

limit_rate 50k;

Here’s how you to add it to http block and apply the limit to all servers.

http {
   ...
   limit 50k;
   ...
}

Bonus Read : How to Remove Trailing Slash in NGINX

Here’s how to limit http bandwidth for a specific server and all its URLs

server {
   server_name www.example.com;
   listen 80;
   ...
   limit_rate 50k;
   ...
}

Here’s how to limit download speed for specific location, e.g /downloads/

location /downloads/ {
   ...
   limit rate 50k;
   ...
}

The above configuration tells NGINX to limit download speed per connection.

Bonus Read : How to Enable NGINX Gzip Compression

However, if users create multiple connections, they can get more bandwidth. So we will use limit_conn_zone directive in http block to limit total amount of shared memory available for managing connections.

limit_conn_zone $binary_remote_addr zone=addr:10m;

Once the allotted memory is exhausted for a connection, NGINX will close the connection.

Similarly, we also add the following line in location block to limit 1 connection per IP address.

limit_conn addr 1;

Bonus Read : How to Enable Leverage Browser Caching in NGINX

Based on our above learnings, here’s a sample configuration that you can use to limit download speed in NGINX.

http {
   limit_conn_zone $binary_remote_addr zone=addr:10m;
   ...

   server {
      ...
      location /downloads/ {
         ...
         limit rate 50k;
         ...
      }
      ...
   }
...
}

Hopefully, this article will help you limit download speed in NGINX. Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free.