Replacing Images with WebP equivalents on the server
WebP provides smaller files and better quality than equivalent JPG or PNG files. The problem is that not all browser support the WebP format, only Chromium-based browsers like Chrome, Opera, plus Edge and Firefox (according to [caniuse.com](https://caniuse.com/#feat=webp). There is no easy way to support browsers that support WebP and those that don't on the same page without modifying the HTML on the pages. Another option is to let the server replace images with their WebP versions for those browsers that support it. By configuring the server to replace the images, where supported, without having to change the HTML on your pages you gain the benefits of the WebP format How to do this will depend on what server you're using. For this, we'll explore configurations for Nginx and Apache. ## Nginx If you're using Nginx the following code will serve WebP images if the browser supports the format and there is an image available on the server. Note that this example is also set up to experiment with The configuration will do the following: 1. Check if the accept header include webp 2. Check if there's a WebP image on the server 3. If there is a file on the server then add the Vary Accept header 4. If the browser supports WebP images then replace the image with the WebP equivalent ```nginx location / { if ($http_accept ~* "webp") { set $webp_accept "true"; } if (-f $request_filename.webp) { set $webp_local "true"; } if ($webp_local = "true") { add_header Vary Accept; } if ($webp_accept = "true") { rewrite (.*) $1.webp break; } if ($http_user_agent ~* "(?i)(MSIE)") { proxy_hide_header Vary; add_header Cache-Control private; } # Rest of configuration goes here } ``` ## Apache The Apache configuration is a set of rewrite rules that will do the same thing for Apache that the configuration for Nginx did. The example below can be used in the global server context (httpd.conf), virtualhost context (