How do i make the link for the secure link module in nginx using python? I\'m looking to use nginx to serve secured files that have expiring links. Link to Nginx Wiki
The accepted answer is incorrect because it only hashes the secret, not the combination of secret, url, and expiration time.
import base64
import hashlib
import calendar
import datetime
secret = "itsaSSEEECRET"
url = "/secure/email-from-your-mom.txt"
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
expiry = calendar.timegm(future.timetuple())
secure_link = "{key}{url}{expiry}".format(key=secret,
url=url,
expiry=expiry)
hash = hashlib.md5(secure_link).digest()
encoded_hash = base64.urlsafe_b64encode(hash).rstrip('=')
print url + "?st=" + encoded_hash + "&e=" + str(expiry)
Corresponding section of a nginx.conf
location /secure {
# set connection secure link
secure_link $arg_st,$arg_e;
secure_link_md5 "itsaSSEEECRET$uri$secure_link_expires";
# bad hash
if ($secure_link = "") {
return 403;
}
# link expired
if ($secure_link = "0") {
return 410;
}
# do something useful here
}