1

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;
    }
Allkin
  • 111
  • 1
  • 3
  • I think is not posible to know size of file from nginx, maybe you need pass request first to php script to get sizeor save your files in diferent dirs, bigger files in one dir and smaller files in other one and per location set limits – Skamasle Mar 23 '17 at 19:30
  • I tried to use $content_length header to get the size in bytes but it seems that limit_rate directive does not allow variables. Anyone knows about this? – Allkin Mar 26 '17 at 09:37

2 Answers2

2

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."

poige
  • 9,448
  • 2
  • 25
  • 52
0

The problem is I can't find a way to get the size of the served file.

You can try to use LUA scripting to find the size of file.

Take a look at openresty project.

Docs: https://github.com/openresty/lua-nginx-module

There is a related openresty module for configuring nginx via lua: https://github.com/fanhattan/lua-resty-rate-limit

You can try to implement similar module for your case.

Nikita
  • 1