This is a very short snippet post so you need to have knowledge about how to configure and customize your NGiNX setup since this is a quick mashup of the config required.
Install WebP.
sudo apt-get install webp
In http {} add the following:
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
This mapping checks whether the browser client supports WebP images, when it does it will set WebP image files as default source.
In location / {} under the server {} add the following:
location ~* ^.+\.(jpe?g|png) {
add_header Cache-Control "public, no-transform";
add_header Vary "Accept-Encoding";
try_files $uri$webp_suffix $uri =404;
expires max;
}
For all jpg, jpeg or png images it will load the WebP variant of it if available, only if the browser client supports it.
I use the following script to convert all jpg, jpeg and png images to WebP while keeping the original in place for browser clients that doesn’t support WebP.
echo "===== Converting images into WebP .webp ====="
for x in `find /var/www/itchy -type f \( -iname \*.jpeg -o -iname \*.jpg -o -iname \*.JPG -o -iname \*.png \)`
do cwebp -quiet -q 80 ${x} -o ${x}.webp;
echo "Converted $x to ${x}.webp"
done
https://itchy.nl/webp-support-for-nginx