nginx .conf, download mp4 file only if there's a specific word in a query param
i have this code:
map $arg_dl $mimetype {
1 application/octet-stream;
default video/mp4;
}
server {
listen 80;
server_name example.com www.example.com;
root /usr/share/nginx/html;
index index.html;
location ~ \.mp4$ {
types {
$mimetype mp4;
}
default_type $mimetype;
}
error_page 404 /404.html;
the problem is that if I insert in the link of the video .mp4? dl = 1 I download the video correctly, but if I open the link of the video with url .mp4 or .mp4? dl = gfgfgf anyway the browser downloads the video. how can i solve? I need to download the video only if there is a one in the query and if there are other parameters to view the video in streaming. how can I do? Thank you
Clearly you cannot set types
and default_type
within an if
block or with a mapped variable. One solution is to use a special URI in a location
marked internal
to handle the specific MIME type you require.
server {
...
root /usr/share/nginx/html;
location ~ \.mp4$ {
if ($arg_dl) { rewrite ^ /download$uri last; }
...
}
location ^~ /download/ {
internal;
alias /usr/share/nginx/html/;
types {}
default_type application/octet-stream;
expires -1;
}
...
}
The ^~
modifier avoids ambiguity with other regular expression locations. The internal
prevents /download
being accessed directly. The location
and alias
should both end with a /
or neither end with a /
.