Using WebP Images Today

How to implement file size saving WebP images using Accept Content Negotiation.

Google Chrome Canary (the developer/early adopter version of Google Chrome) has recently added an "image/webp" accept header to image requests, which means that rather than needing to employ some sophisticated client side detection and fallback to useĀ WebP. It's possible to more simply deploy WebP using image request headers, at least for browsers that send the image/webp Accept header.

Configuring Nginx to negotiate based on this header is actually very straightforward as this Nginx configuration example shows (source):

location / {
  # check Accept header for webp, check if .webp is on disk
  if ($http_accept ~* "webp") { set $webp T; }
  if (-f $request_filename.webp) { set $webp "${webp}T"; }

  # if WebP is supported, and WebP is on disk, serve it!
  if ($webp = TT) {
    add_header Vary Accept;
    rewrite (.*) $1.webp break;
  }
  # ...
}

This Nginx configuration code firstly checks to see if the user agent has sent the Accept header for WebP. If so, it then checks to see if a WebP image exists and then if both conditions are met the request is rewritten to serve the WebP image and the Vary: Accept header is added.

Tagged with:

You might also like...

Edge adopts Chromium rendering engine

Michael Walsh by Michael Walsh