January 25, 2019

Adding WebP support to NGiNX

A short guide about how to add WebP image support to the NGiNX webserver.

Adding WebP support to NGiNX

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 must 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 eighty. 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