Search code examples
nginxcdnimagefilter

nginx image_filter ngx_http_image_filter_module alias problem


good day everyone, new time poster, tried looking for a solution to my issue but can't really find anything. I am not a programmer, just a curious person trying to figure things out, so apologies for the non-specific language.

I am setting up a personal space to stock my pictures; I want to access them from the internet no matter where I am.

To reduce load times I am trying to setup the image_filter module in nginx and this is where my problem lies. all the quick guides I've read specify a static alias folder where all images should be stored, but my images will be stored in separate folders. the structure is more or less as follows:

/var/www/travel/trip1/image_folder
/var/www/travel/trip2/image_folder
/var/www/travel/trip3/image_folder

and so on. this is important because the site will also serve as backup, and I don't want to 'mix' all the images in one single folder.

so based on the trip* number, the alias should refer to the corresponding subfolder image_folder. no matter what I try, nginx will only serve the image if the static alias is configured:

location ~ "^/media/(?<width>\d+)/(?<image>.+)$" {
alias /var/www/travel/trip1/image_folder/$image;
image_filter resize $width -;
image_filter_jpeg_quality 75;
image_filter_buffer 8M;
}

is there any way to make the alias 'dynamic'? so if I load the trip1 index page, the images are loaded from /var/www/travel/trip1/image_folder, if I load the trip2 index page they are loaded from /var/www/travel/trip2/image_folder and so on?

thanks in advance. leo


Solution

  • You can capture the remainder of URI and process it, like this:

    location /static {
        autoindex on;
        alias /home/pi/rpiz-site/staticfiles/;
    
        location ~ \.png$ {
            image_filter resize 200 200;
        }
    }
    

    Notice this nested location directive part, which actually lets you to capture the remaining of the initial location directive URI, which is the same as you call it "dynamic" alias:

    location ~ \.png$ {
        image_filter resize 200 200;
    }
    

    This approach works for my case perfectly: serve static files and if it is a png file, resize it to 200x200px.