How serve automatically .webp images with Nginx

If your website uses several transparent png images the most convenient and effective optimization is to convert all the media assets to webp format… this will cut heavily the pageload because webp could weigh up to 10% of the original image.

There is a way with nginx to hijack the request from standard images formats (.jpg, .png, etc) to the webp, so this way you don’t have to edit all the image links on the website to take advantage of using the next gen image format… Just follow this tutorial, what you need is a .webp image copy in the same folder of the original (named “filename.extension.webp” along the original “filename.extension”).

If the webp copy is not there, it doesn’t break the image link because nginx will checks first that the image exists, otherwise the original one is served.


Nginx configuration

You need to edit the main server block so you need to open the linux bash then edit the

sudo nano /etc/nginx/sites-enabled/default

Before the beginning of the server block add:

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

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 *