Nginx – How to limit the maximum network speed in the whole Virtual Host

apache-2.4nginxrate-limitingreverse-proxy

Background

I have a Apache (with NginX Reverse Proxy) as web server. I have a forum and a image host service running.

But as you know, image host service causes a lot of network bandwidth (Mbps). I want to reserve some of the bandwidth to my forum by limiting the maximum traffic in the virtual host of the image host service.

What I have done:

Apache

I have installed the mod_bw module in order to limit the maximum bandwidth. It seems working very well because it slows down the page loading. But this is not enough. I need to limit the download speed also and now the image will download at full speed. So this one is not working (or partly working) but I will keep it in the httpd.conf.

Nginx

Built-in module limit_rate is working for downloading image. So it looks like if combining two modules, the image host service can run at a restricted environment. But wait a minute … When I download multiple images at once, all images will download at the same limited speed. For example I set to 50KB/s, if I download an image, the maximum speed is 50KB/s. And then I download another image file before the last one completed, the download speed of both images are 50KB/s, in total is 100KB/s.

This is not what I need.

What I actually need is:

No matter how many concurrent users are browsing the image host web page at the same time, they can only share the total bandwidth that set to 50KB/s. (Just an example, I will increase this)

As I have both Apache and NginX, I don't care combining multiple modules to help me to reach the objective. Please help me to solve the problem, thank you very much!

Best Answer

If you need to set a limit to the connections, you should be able to do it with limit_zone and limit_conn directives. Example:

Inside your server block configuration:

limit_rate 128K; limit_zone one $binary_remote_addr 10m;

Inside your location block configuration:

limit_conn one 10;

In this example, it would allow 10 connections per IP with 1 Mbit each.