Nginx Image_Filter Resize and Convert Images to Webp

I want to serve resized and converted png/jpg/jpeg images through image_filter in nginx to serve images in webp format. Is there any options to do so via try_files to rewrite path or another way without installing other extensions to nginx?

set $width "-";
      
if ($arg_w != '') { 
    set $width $arg_w; 
}

location ^~ /common/images/\.*\.(png|jpeg|jpg) {
    add_header X-Nginx-Image Resized;
    image_filter resize $width -;
    expires 12M;
    add_header Cache-Control "public";
}
2

1 Answer

I have organized the comments to make them look neat.

[ Source: Andrei Musteata ]

I've found a solution for me, that works well.

So, if I have converted image in webp, it resizes and serve, otherwise, it resizes my base image without converting.

set $width "-"; 

if ($arg_w != '') { 
    set $width $arg_w; 
}

location ~* "^(?<path>.+)\.(png|jpeg|jpg)$" { 
    try_files $path$webp_ext $path$file_ext =404; 
    add_header X-Nginx-Image Resized; 
    image_filter resize $width -; 
    expires 12M; 
    add_header Cache-Control "public"; 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest