Search code examples
nginxnginx-locationnginx-config

Nginx Rewrite Location to subfolders


I need help to determine what's the best way to split characters to sub-folders? What I specifically need is to Rewrite url /file/12345.jpg to /1/2/3/4/5/12345.jpg FS path. (numbers are not restricted to only these - they could be in any combination of digits, for example: /file/123.jpg, /file/123456789.jpg and etc.)

This is base location.

location ~ ^/file/(.+)\.(.+)$ {
   ....
}

One possibility is to describe all variations:

location ~ ^/file/(\d)\.(.+)$ {
   alias /file/$1/$1.$2;
}
location ~ ^/file/(\d)(\d)\.(.+)$ {
   alias /file/$1/$2/$1$2.$3;
}

and etc

but it's ugly and not productive.


Solution

  • /file/12af5.jpg to /1/2/a/f/5/12af5.jpg:

    location ~ ^/files/((\w)(\w)(\w)(\w)(\w))\.(.*) {
      rewrite "/$2/$3/$4/$5/$6/$1.$7" break;
    }
    

    For more dynamic functionality, consider using rewrite_by_lua (custom nginx build required) or use OpenResty, which includes it out of the box. You could also proxy requests to a Python/Node/Php/etc backend server to dynamically redirect with your language of choice.