nginx, alternative to if inside location to download or streaming a file
i have a problem. Inside nginx.conf i want to download a file only if there's in a query param "?dl=1" otherwise i want to stream the video mp4.
I have write this code:
location ~\mp4 {
if ($args_dl = "1") {
types { application/octet-stream (.mp4); }
default_type application/octet-stream;
}
}
This code doesn't work because there's a if statement inside location. how should i change it to be able to perform the same operation? Thanks
Solution 1:
You might be able to use nginx map
feature for this. Add the following to http
level in nginx config:
map $arg_dl $mimetype {
default video/mp4;
1 application/octet-stream;
}
This one sets value for $mimetype
variable based on the value of URL query argument dl
. If dl
is 1, mimetype is set to application/octet-stream
, otherwise it is set to video/mp4
.
And then use the mapped variable in location
as follows:
location ~ \.mp4$ {
types {
$mimetype mp4;
}
default_type $mimetype;
}
This is completely untested, and it is the first time using a mapped variable inside types
.
I also improved the location
match to explicitly match .mp4
extension. location ~ \mp4
could match any URL that contains mp4
, so it can cause issues.