How to serve webp images using nginx

WebP images are used nowadays to improve site speed. It is a great tool for Business Owners out there developed by Google to help speed up their websites. In this post, you will get to know how you can server webp images through Nginx when requesting png / jpg images.

I assume you have already converted png and jpg images into webp; if not, click here to know how you can convert.

Configure Nginx

location ~* ^.+.(jpg|jpeg|png)$ {
    try_files "$uri.webp" $uri =404;
}

Above code explanations:

When you access jpg, png or jpeg image, Nginx will go to above block. It will search for the file with .webp extension in the same folder where you normal images are kept.

For example: you are trying to access http://example.com/test.png then it will search for /test.png.web to be retrieved in response. If the webp image does not exist, it will return 404 Not Found error.

Make sure the webp files are accessible by full path at server. For example : the test.png file is inside /var/www/images then your nginx config would be like:

location ~* ^.+.(jpg|jpeg|png)$ {
    root "/var/www/images";
    try_files "$uri.webp" $uri =404;
}

Checkout the Content-Type in below image.

 

Let me know if you face any issues.

Thanks for reading 🙂

Leave a Reply

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