nginx - limiting bandwidth usage per server block

In Apache we have some great solutions for limiting the bandwidth usage per vhost, like mod_bandwidth. However, since I started using nginx, I couldn't find a way of limiting and monitoring the bandwidth usage for each server block.

I would like to hear some suggestions regarding monitoring and limiting bandwidth usage per server block on nginx.


Solution 1:

You can use limit_rate to limit the bandwidth. For me this also works on the community version of nginx.

For example the bandwidth can be limited to 1000 Bytes per second for the whole server block like this:

server {
    listen 80;

    location / {
        limit_rate 1k;
    }
}

Solution 2:

Nginx Plus has built in options to throttle bandwidth per host.

If you want to achieve it over the community version of nginx you have 2 options: (As it's only inclduing per IP pooling of bandwidth.)

1: Limit the bandwidth of the whole nginx process, using external tools or ip-tables.

2: Serve this specific content via proxy-pass to lighttpd and set a server-throttle in lighttpd

server.kbytes-per-second = 6250

If downloads.domain.net would be the thing we want to throttle, Lighthttpd would have the following config:

server.port = 81
server.document-root = "/path/to/downloads"
index-file.names = ( )

Nginx:

server {
    listen 80;
    server_name downloads.domain.net;

    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://127.0.0.1:81;
    }
}

Of course you can also proxy by specific files, folder etc.

Ultimately: Using this and also ip-table throttling the whole port 80 traffic ( and 443 ) is the ultimate solution in case you don't want to go over a specific point of bandwidth. ( For example VoIP services can require a hard limit on http traffic )