Adding WebP support to NGiNX

snippets Jan 25, 2019

This is a short snippet post on how to add WebP support to your NGiNX server. So you need to know how to configure and customize your NGiNX setup.

To be able to use WebP, we first have to install it using the following command.
sudo apt install webp

Configure NGiNX by adding the following inside the http {} config block.

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.

Add the following inside the server {} config block

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.

To convert the images to WebP format I use the following script. It will scan the directory where you have your images located at and convert them to WebP with the image quality of 80. The original files stay intact so that NGiNX can still serve them to browsers that don'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
Change /var/www/itchy to suit your setup

Buy Me A Coffee

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.