I want to optimize some images on my site using WebP format.
Webp images are highly compressed jpegs and pngs with the help of algorithm developed in Google.
However, webp images can be displayed only in modern Chrome and Opera.
If browser supports webp it specifies image/webp
in Accept
HTTP header.
It is good idea to check in nginx if browser supports webp format and if webp version for image exists on disk and if so - serve webp image, if not - serve default image.
For example:
http://example.com/dog.png
, Accept: image/webp, image/png, image/jpeg
. nginx must send dog.png.webp
http://example.com/dog.png
, Accept: image/png, image/jpeg
. nginx must send dog.png
A little 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
That's ok. But I am using CloudFlare CDN to speed up asset delivery.
With such image serve conditions we must add header Vary: Accept
so cacheing in browser and proxy will work properly. But there is a problem! CloudFlare supports only Vary: Accept-Encoding
. This is described here.
Clients will get version of image which was cached by CloudFlare first (webp or regular) and if client doesn't supports webp it will not see image and it is terrible.
Is there any solutions?
With the example of having dog.png
and dog.jpg
.
Have your backend serve a /dog
(without any file extension) which will always respond with Cache-Control: private
and thus be never cached by the CDN.
Your backend will now always get hit for that url, and can analyze the headers like the Accept
header, and decide if the browser needs png
/jpg
or if you can use more advanced format like webp
(Firefox, Chrome), JPEG 2000
(Safari) and JPEG XR
(IE9+).
Now the backend forwards (301
Moved Permanently
) to either dog.png
and dog.jpg
or the converted dog.webm
, dog.jp2
and dog.jxr
as needed.
Those static image files are served with appropriate caching headers to be cached by the CDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With