RewriteEngine On
# The same rules as the ones Robin writes (WRIO\WEBP\Server::htaccess_update_webp_rules()): only the Accept
# header decides, because Vary: Accept cannot describe a choice made from the user agent.
##### AVIF first, for the browsers that accept it (ex. test.jpg.avif) #####
RewriteCond %{HTTP_ACCEPT} image/avif
RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png)$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.avif -f
RewriteRule ^(.+)$ $1.avif [NC,T=image/avif,L]
##### TRY FIRST the file appended with .webp (ex. test.jpg.webp) #####
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png)$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.webp -f
RewriteRule ^(.+)$ $1.webp [NC,T=image/webp,L]
##### IF NOT, try the file with replaced extension (test.webp) #####
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png)$
RewriteCond %{DOCUMENT_ROOT}/%1.webp -f
RewriteRule (.+)\.(?:jpe?g|png)$ $1.webp [NC,T=image/webp,L]
# Every answer for a JPEG or PNG URL depends on the Accept header, also when the original is served.
Header merge Vary Accept
AddType image/webp .webp
AddType image/avif .avif