Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode and decode pathname in nginx

Normally files can be accessed at:

http://example.com/cats/cat1.zip

I want to encode/encrypt the pathname (/cats/cat1.zip) so that the link is not normally accessible but accessible after the pathname is encrypted/encoded:

http://example.com/Y2F0cy9jYXQxLnppcAo=

I'm using base64 encoding above for simplicity but would prefer encryption. How do I do about doing this? Do I have to write a custom module?

like image 819
user3666697 Avatar asked Dec 22 '17 05:12

user3666697


1 Answers

You can use a Nginx rewrite rule rewrite the url (from encoded to unencoded). And, to apply your encoding logic you can use a custom function (I did it with the perl module).

Could be something like this:

 http {
  ...
    perl_modules perl/lib;
    ...
    perl_set $uri_decode 'sub {
      my $r = shift;
      my $uri = $r->uri;
      $uri = perl_magic_to_decode_the_url;
      return $uri;
    }';
    ...
    server {
    ...
      location /your-protected-urls-regex {
        rewrite ^(.*)$ $scheme://$host$uri_decode;
      }
like image 70
Gonzalo Matheu Avatar answered Oct 20 '22 13:10

Gonzalo Matheu