Serving WebP images in WordPress with Nginx

WebP in Chrome

WebP is Google’s image format for the web, sporting much smaller file sizes while conserving image quality. The excellent WordPress plugin EWWW Image Optimizer  can since v. 2 create WebP versions of your images, and help you with serving them to compatible browsers only (as of today Chrome and Opera) via Apache rewrite rules.

But what about Nginx?

As usual it’s not as simple as pasting code into an .htaccess file, but if you run Nginx on your own server or VPS it’s pretty straightforward.

  1. Add “image/webp webp” to the file /etc/nginx/mime.types (So that Nginx recognize the MIME type.)
  2. Add
    map $http_accept $webp_suffix {
    default "";
    "~*webp" ".webp";
    }
    to your main Nginx config file: /etc/nginx/nginx.conf .
  3. Add
    location ~* ^/wp-content/.+\.(png|jpg)$ {
    add_header Vary Accept;
    try_files $uri$webp_suffix $uri =404;
    }
    to the server block for the site. Mine is /etc/nginx/sites-enabled/example.com .
  4. Restart nginx

Now it’s not evident that you’re seeing WebP and not Jpeg or PNG in your browser. What worked for me as a test was to compare MIME types and file sizes between Chrome and Firefox in their developer tools. See the screenshot above.

Thanks to Eugene Lazutkin for the comprehensive writeup on serving files with nginx conditionally!

This worked for me. See them in action on www.pekoe.se! // Moved to PageSpeed-Nginx, which does all the work for you. //

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s