Secure_Link

最後更新: 2021-11-04

 


Installation

 

It is not included by default when you build NGINX from source;

enable it by including the "--with-http_secure_link_module" argument to the configure command.

 


Nginx Settings

 

server {
    listen       80;
    server_name  192.168.88.20;
    location ~ /\.ht { deny  all;}
    location / {
        root   /home/vhosts/IP/public_html;
        index  index.html index.htm;
    }
    location /files {
        if ($request_uri ~ "/files/([\w\-_]+)/(\d+)/(.*)") {
                set $hash_md5 $1;
                set $expires  $2;
                set $filepath $3;
        }
        # For debug
        #return 200 $expires#$filepath#MySecret;
        secure_link $hash_md5,$expires;
        secure_link_md5 "$expires#$filepath#MySecret";
        if ($secure_link = "") {return 403;}
        if ($secure_link = "0") { return 410;}
        rewrite ^ /secure/$filepath;
    }
    location /secure/ {
        internal;
        # expires 3h;
        alias /home/vhosts/IP/files/;
    }
}

說明

secure_link

Syntax: secure_link $hash_md5,$expires;

Defines a string with variables from which the checksum value and lifetime of a link will be extracted.

secure_link_md5

Syntax: secure_link_md5 expression;

Defines an expression for which the MD5 hash value will be computed and compared with the value passed in a request.

$secure_link

The status of these checks is made available in the $secure_link variable.

  • NULL: checksums are different
  • 0: expired
  • 1: Ok

URL

The MD5 hash value passed in a request is encoded in base64url

If a link has a limited lifetime, the expiration time is set in seconds since Epoch

base64url

where the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_'

require omitting the padding '=' signs to avoid them being confused with field separators

 


建立 Link

 

# 過期時間

expires=$(( $(date +%s) + 60 )); echo $expires

# base64url 's md5

echo -n "$expires#pricelist.html#MySecret" | \
    openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =

http://192.168.88.20/files/ENk1Auzts1nLEolCoYZpow/1636003841/pricelist.html