Nginx – file path encryption
There was a task to set up encryption in the links of paths to media files for placing movies on the site.
We use nginx for this:
rewrite /([a-zA-Z0-9_\-]+)/([0-9]+)/(.+)\.mp4$ /$3.mp4?md5=$1&time=$2;
location / {
secure_link $arg_md5,$arg_time;
secure_link_md5 SECRET_WORD$uri$arg_time$remote_addr;
if ($secure_link = "") {
return 403;
}
if ($secure_link = "0") {
return 404;
}
access_log off;
internal;
mp4;
mp4_buffer_size 512K;
mp4_max_buffer_size 25m;
}
Above, we encrypt file paths with .mp4 extension.
SECRET_WORD is the secret word for encryption, which is then used in the PHP script to get links to the file:
<?php
$name = '/directory/file.mp4';
$secret = 'SECRET_WORD ';
$time = time() + 18000;
$link = base64_encode(md5($secret.'/'.$name.$time.$_SERVER['REMOTE_ADDR'], TRUE));
$key = str_replace("=", "", strtr($link, "+/", "-_"));
$encoded_url = "https://HOST/$key/$time/$name";
echo $encoded_url;
?>
In the $time variable, we indicate the expiration date of the link, in this case the link will be valid for 3 hours.