Unable to serve WebP images with CloudFlare?

I want to optimize some images on my website in WebP format.

Webp images are compressed jpegs and png using an algorithm developed by Google.

However, web images can only be displayed in modern Chrome and Opera. If the browser supports webp, it indicates image/webp in the Accept HTTP header.

It is a good idea to check nginx if the browser supports the webp format, and if the webp version for the image exists on the disk, and if so, execute the web image, if not, specify the default image.

For instance:

http://example.com/dog.png , Accept: image/webp, image/png, image/jpeg . nginx should send dog.png.webp

http://example.com/dog.png , Accept: image/png, image/jpeg . nginx should send dog.png

A bit more explanation can be found in this nginx configuration https://github.com/igrigorik/webp-detect/blob/master/nginx.conf and https://github.com/kavu/sprockets-webp #nginx

This is normal. But I use CloudFlare CDN to accelerate asset delivery.

Under these conditions of working with images, we must add the Vary: Accept header, so caching in the browser and proxy server will work correctly. But there's a problem! CloudFlare only supports Vary: Accept-Encoding . This is described here .

Clients will receive a version of the image that was first cached by CloudFlare (webp or regular), and if the client does not support webp, it will not see the image, and this is terrible.

Are there any solutions?

+6
source share
1 answer

With an example of the presence of dog.png and dog.jpg .

  • Let your backend serve /dog (without a file extension), which always responds with Cache-Control: private and therefore will never be cached by CDN.

  • Your server will now always receive this URL and can parse headers such as the Accept header and decide if the browser needs png / jpg or if you can use a more advanced format like webp (Firefox, Chrome) , JPEG 2000 (Safari) . ) and JPEG XR (IE9 +) .

  • Now the backend dog.png forward ( 301 Moved Permanently ) is either in dog.png and dog.jpg or in converted dog.webm , dog.jp2 and dog.jxr as necessary.

  • These static image files are provided with corresponding caching headers that should be cached by the CDN.

0
source

All Articles