Search code examples
nginxwebserverstatic-files

Nginx deploy static file in dynamic sub folder


My website root (/var/www/static.website.ext/public_html) is organized as follows:

images
|___ 61
     |___ 6105495099f49473.png
|___5f
     |___ 5fb969a00a4832d2.png
schema
|___ satic_file.png

As you can see the folders "61" and "5f" are generated dynamically (when loading the static file) from the name of the image. (first two characters)

My goal is the following:

https://static.website.ext/images/6105495099f49473.png  = display 6105495099f49473.png image (located in /images/61/61...)

How can I do in Nginx ? In Apache just use mod_rewrite, or alternatively mount an index.php file in the /images/ folder with a dispatcher.

But the performance would not be (I guess) like distributing directly from Nginx


Solution

  • Use a regular expression location to capture the parts of the URI you require to build the path to the files. See this document for details.

    For example:

    root /var/www/static.website.ext/public_html;
    
    location ~ ^(/images)(/..)(.*)$ {
        try_files $1$2$2$3 =404;
    }