Nginx location regex: unknown “1” variable

nginx

I wanna make some video downloadable, but my strategy doesn't seem to work…

  location ~* ^/(this-video.mp4)(/.*)$ {
    alias /some/path/this-video.mp4;
    add_header Content-Type 'video/mp4';
    if ( $2 = "/dl" ) {
      add_header Content-Disposition 'attachment; filename="$1"';
    }
  }

Error:

# nginx -t

nginx: [emerg] unknown "1" variable
nginx: configuration file /etc/nginx/nginx.conf test failed

# nginx -v
nginx version: nginx/1.6.2

Any idea what I did it wrong?

EDIT:

BTW, this one pass the test:

  location ~* ^/(this-video.mp4)(/.*)$ {
    alias /some/path/$1;
    add_header Content-Type 'video/mp4';
    #if ( $2 = "/dl" ) {
    #  add_header Content-Disposition 'attachment; filename="$1"';
    #}
  }

# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

So it must have something to do with quotes?

EDIT2

Nginx docs state:

A condition may be any of the following:

a variable name; false if the value of a variable is an empty string or “0”;

So if /dl is not provided in the url, then $2 should be an empty string?

Best Answer

The problem appears to be that the numeric captures do not make it through the if block, presumably because the if condition can also be a new regular expression. You can solve the problem by using named captures instead, for example:

location ~* ^/(?<filename>.+\.mp4)(?<suffix>/.*)$ { ... }

However, it is not advisable to use some types of if blocks, so you might consider using two location blocks instead:

location ~* ^/(.+\.mp4)/dl$ {
    alias /some/path/$1;
    add_header Content-Type 'video/mp4';
    add_header Content-Disposition 'attachment; filename="$1"';
}
location ~* ^/(.+\.mp4) {
    alias /some/path/$1;
    add_header Content-Type 'video/mp4';
}

Or something simpler for the second location, if applicable, like a prefix location containing a root directive.