Nginx throttle download speed based on filesize

nginxrate-limiting

I am using nginx/1.11.11 compiled from the source with the mp4 module and I am serving video files from 300MB size up to 8GB.

I am thinking of implementing a throttle system similar to google's drive.
If the size of the file is big set a larger the limit_rate and if the file size is small set a smaller limit_rate.
The problem is I can't find a way to get the size of the served file.

My default.conf file looks like this:

server {
    listen       80;
    server_name  _; # change this for your server
    root /var/www;
    index index.php;
    client_max_body_size 5G;
    proxy_read_timeout 60000000;

    # handle requests to the API
    location ~ /api/v2/(.+)$ {
        if (!-e $request_filename) { rewrite ^/api/v2/(.*) /api/v2/index.php?_page_url=$1 last; }
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param MOD_X_ACCEL_REDIRECT_ENABLED on;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        if (!-e $request_filename) { rewrite ^/(.*) /index.php?_page_url=$1 last; }
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_read_timeout 180000000;
        fastcgi_param MOD_X_ACCEL_REDIRECT_ENABLED on;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    location / {
        if (!-e $request_filename) {
                rewrite ^/(.*) /index.php?_page_url=$1 last;
        }
    }
    location /files/ {
        root /var/www;
        aio threads;
        internal;
        mp4;
        limit_rate_after 5m;
        limit_rate 400k;
    }

    # these locations would be hidden by .htaccess normally
    location /core/logs/ {
        deny all;
    }

Best Answer

Nginx also has limit_rate_after size: "Sets the initial amount after which the further transmission of a response to a client will be rate limited."