How to limit http connections in Nginx

In this tutorial, we want to discuss about how to limit http connections in Nginx.
for some reason, there may be need to limit access to http resources. for example you want to limit bandwidth per IP or number of connection that an IP can establish.

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

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 Connections

For limiting number of connections, we use limit_conn_zone 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_conn_zone $binary_remote_addr zone=addr:10m;

this line tells Nginx to define a zone called “addr” and assign 10mb shared memory to it and apply this limit based on remote IP address.
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_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 Module ngx_http_core_module

3- Test limiting

to test if our configuration works properly, we put a 100MB 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.