public
Last active

Apache: Detecting WebP support with Header Vary Accept

  • Download Gist
.htaccess
ApacheConf
1 2 3 4 5 6 7 8 9 10 11 12
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
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

I see that you're adding 'Accept' to the Vary header, which is great, but you're also varying the content based on the User-Agent, so that would have to be included in the Vary header for it to be correct.

Fortunately Chrome is now sending "image/webp" in the Accept header for image requests, (although not on html requests unfortunately) so you should be able to remove the User-Agent detection. Users will get the webp version for resources included on a page, but not if they request the image directly.

Sergej: Just checked your website, but in the latest Chrome Beta I see PNG's. Is this .htacess not working any more?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.