Last active
July 19, 2024 16:14
-
-
Save bftanase/cbae1f9fc69bb4f9cb86 to your computer and use it in GitHub Desktop.
generate URL for nginx secure_link
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param $baseUrl - non protected part of the URL including hostname, e.g. http://example.com | |
* @param $path - protected path to the file, e.g. /downloads/myfile.zip | |
* @param $secret - the shared secret with the nginx server. Keep this info secure!!! | |
* @param $ttl - the number of seconds until this link expires | |
* @param $userIp - ip of the user allowed to download | |
* @return string | |
*/ | |
function buildSecureLink($baseUrl, $path, $secret, $ttl, $userIp) | |
{ | |
$expires = time() + $ttl; | |
$md5 = md5("$expires$path$userIp $secret", true); | |
$md5 = base64_encode($md5); | |
$md5 = strtr($md5, '+/', '-_'); | |
$md5 = str_replace('=', '', $md5); | |
return $baseUrl . $path . '?md5=' . $md5 . '&expires=' . $expires; | |
} | |
// example usage | |
$secret = 'the_secret_key_configured_in_nginx'; | |
$baseUrl = 'http://example.com'; | |
$path = '/path/to/file.zip'; | |
$ttl = 120; //no of seconds this link is active | |
$userIp = '195.99.99.99'; // normally you would read this from something like $_SERVER['REMOTE_ADDR']; | |
echo buildSecureLink($baseUrl, $path, $secret, $ttl, $userIp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UPD. did it in this way
is there any possibility to rewrite or redirect to php script using wildcards in case of expired image?
e.g. something like
but then the php file is saved and not loaded in the browser.
When I enter in browser URL https://this.server/local_folder/picture.php?id=XXXXX&size=th&idx=01&tkey=XXXXXXXXXXX - all is loading fine (image with filters is shown)
There's a block in server setting, which handles php scripts
when I use
all working - URL is redirected, image is shown. But how to use rewrite here? Better solution is to keep original URL
Any ideas?