How serve automatically .webp images with Nginx

if your site uses transparent png the most convenient optimization is to convert that images to webp because they weigh up to 10% of the original. There is a way with nginx to hijack the request to jpg or png images on the webp version if available

Before the beginning of the server block add:

map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}

then inside the generic server block (or the main server block depends on your configuration):

    location ~* ^.+\.(png|jpg|jpeg)$ {
            add_header Vary Accept;
            try_files $uri$webp_suffix $uri =404;
    }

Then finally, the server block will look like this:

Post navigation

You might be interested in...

No comments yet, be the first!

Comments

Your email address will not be published. Required fields are marked *