How to limit HTTP bandwidth in Nginx

In this tutorial, we want to show how to limit http bandwidth in Nginx.
By applying this setting, a typical client will be able to download content at a maximum speed kilobytes per second we determine.

Here is our environment:
OS: CentOS 7 linux on VMWare
Firewall: firewalld
SELinux: enforcing
IP Address: 192.168.147.128

1- Install Nginx

Here we assume you have installed nginx before. if you have not done that, refer to how to install Nginx web server on CentOS 7 Linux.

2- limit http bandwidth

For limiting http bandwidth, we use limit_rate directive. you can use it in location {}, server {} and http {} directive. here we use it in http {} directive and paste the following line in it:

# limit_rate 50k;

this line tells Nginx to limit bandwidth to 50 kilobytes per second for a single connection. this means that client can open more than one connection and get more bandwidth. so we need to limit number of connections also:

# limit_conn_zone $binary_remote_addr zone=addr:10m;

we put above line in http{} directive.

# limit_conn addr 1;

in this tutorial, we assume that there is directory called “download/” in /var/www/html” and Nginx has been configured to use “/var/www/html” directory as root document.
so we want to apply limit on “download/” directory.find directive related to “download” and add the following line in it:

location /download/ {
limit_rate 50k;
limit_conn addr 1;
}

this line tells Nginx to limit number of connections to 1 per IP address, because previously we used “$binary_remote_addr” as key.
for more information about usable keys, refer to https://nginx.org/en/docs/http/ngx_http_core_module.html?&_ga=2.240776960.2093580261.1579695212-898961125.1578754976#variables
so our final configuration will be something like this:

http {
limit_conn_zone $binary_remote_address zone=addr:10m

server {
root /var/www/html;
limit_conn addr 5;

location / {
}

location /download/ {
limit_conn addr 1;
limit_rate 50k;
}
}
}

3- Test limiting

to test if our configuration works properly, we put a 700MB file in “download” directory and download it with a download manager like IDM. also we configure IDM to establish more than 1 connection.
to approve that our configuration works properly, IDM must be able to establish no more than 1 connection.