Using WebP images with .htaccess

What’s a WebP image?

You might have already heard about them when Google introduced it 2013. Unfortunately the mainstream use of them didn’t take of as they might have expected.

WebP is a new open image format that uses both lossless and lossy compression. It was developed to reduce image file size to speed up web page loading: its principal purpose is to supersede JPEG as the primary format for photographs on the web. WebP now supports animated images and alpha channel (transparency) in lossy images so they can also supersede PNG images.

How do I start?

First of all you need to convert your old JPGs and PNGS to the Webp format. You can use Grunt, bla, bla. I use a imagemin plugin called imagemin-webp. You can also download more tools like plugins for Photoshop and Gimp over at Google.

To render your images on your page there are some different approaches. The easiest way, I feel, is to use the .htaccess technique. Paste this code below into your .htaccess and when your server requests an image, it will first see if there’s a WebP image in the same search path with the same name and use it if the users browser supports it.

Here is a GitHub repository for the code with a small demo.

<IfModule mod_rewrite.c>
  RewriteEngine On

  # Check if browser support WebP images
  RewriteCond %{HTTP_ACCEPT} image/webp

  # Check if WebP replacement image exists
  RewriteCond %{DOCUMENT_ROOT}/$1.webp -f

  # Serve WebP image instead
  RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
</IfModule>

<IfModule mod_headers.c>
    Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp