A Rule Line by Line

A Rewrite Rule Read Line by Line

This file serves cat.webp for cat.jpg to browsers that accept WebP, under the same URL, and the original when no twin exists. It needs mod_rewrite, mod_headers and mod_mime, AllowOverride FileInfo and FollowSymLinks.

/var/www/example/images/.htaccess: WebP when the browser accepts itXML
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_ACCEPT} image/webp [NV]
  RewriteCond %{REQUEST_FILENAME} ^(.+)\.(?:jpe?g|png)$ [NC]
  RewriteCond %1.webp -f
  RewriteRule ^(.+)\.(?:jpe?g|png)$ $1.webp [NC,END]
</IfModule>
AddType image/webp .webp
<IfModule mod_headers.c>
  <FilesMatch "\.(?i:jpe?g|png|webp)$">
    Header append Vary Accept
  </FilesMatch>
</IfModule>
Output of 49
$ for f in cat.jpg dog.png; do for a in 'image/avif,image/webp,*/*' 'image/*'; do
>   printf '%-8s %-26s ' $f "$a"; curl -so /dev/null -H "Accept: $a" \
>   -w '%{content_type} %{size_download} %header{vary}\n' localhost:8105/images/$f; done; done
cat.jpg  image/avif,image/webp,*/*  image/webp 3100 Accept
cat.jpg  image/*                    image/jpeg 5000 Accept
dog.png  image/avif,image/webp,*/*  image/png 4000 Accept
dog.png  image/*                    image/png 4000 Accept

One URL gave 3,100 bytes of WebP or 5,000 of JPEG, each with Vary: Accept; dog.png, with no twin, stayed a PNG.