I'm having problem to serve webp format images through htaccess. I have followed https://www.digitalocean.com/community/tutorials/how-to-create-and-serve-webp-images-to-speed-up-your-website and https://gist.github.com/seeekr/2415528 links code. before helping me, I want to clarify something. First, images are in many subfolders. for example: public_html/wp-content/uploads/2023/10, 2024/02, 2024/05 like that. Second, in every folder i have image.jpg format and image.jpg.webp format. server is not picking the image.jpg.webp. I want to use that format. third, my .htaccess is in the public_html folder. Here are the codes I tried:
<IfModule mod_rewrite.c>
RewriteEngine On
# Check if browser supports WebP
RewriteCond %{HTTP_ACCEPT} image/webp
# Check if WebP version of the image exists
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
# Serve the WebP version if available
RewriteRule (.+)\.(jpg|jpeg|png|gif)$ $1.webp [T=image/webp,E=Cache-Control:vary=webp]
# Add the Vary header to inform browsers and proxies about WebP support
<IfModule mod_headers.c>
<FilesMatch "\.(jpg|jpeg|png|gif|webp)$">
Header append Vary Accept
</FilesMatch>
</IfModule>
AddType image/webp .webp
then I have used:
RewriteCond %{REQUEST_FILENAME} (.+)\.(jpe?g|png|gif)$
RewriteCond %1\.webp -f
RewriteCond %{QUERY_STRING} !type=original
RewriteRule (.+)\.(jpe?g|png|gif)$ $1.webp [NC,T=image/webp,E=webp,L]
then:
# Check if the requested file is a supported image format
RewriteCond %{REQUEST_FILENAME} \.(jpg|jpeg|png|gif)$ [NC]
# Check if a corresponding WebP version exists in the same directory
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.webp -f
# Serve the .webp version instead
RewriteRule (.+)\.(jpg|jpeg|png|gif)$ $1.$2.webp [T=image/webp,E=accept:1,L]
and then:
# Only target images within the wp-content/uploads folder (and its subfolders)
RewriteCond %{REQUEST_URI} ^/wp-content/uploads/ [NC]
# Check if a WebP version of the file exists (recursively in subfolders)
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.webp -f
# Serve the .webp version if it exists
RewriteRule (.+)\.(jpg|jpeg|png|gif)$ $1.$2.webp [T=image/webp,E=accept:1,L]
also used this one:
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME}.webp -f
RewriteRule ^/?(.+?)\.(jpe?g|png)$ /$1.$2.webp [NC,T=image/webp,E=EXISTING:1,E=ADDVARY:1,L]
and finally I have tried this one too:
RewriteCond %{REQUEST_URI} ^/uploads/2023/10/(.+)(?:\.jpe?g|\.png)$
RewriteCond %{DOCUMENT_ROOT}/uploads/2023/10/%1.webp -f
RewriteRule ^/uploads/2023/10/%1.webp [L,T=image/webp,E=accept:1]
none of them picks image.jpg.webp format, always chooses image.jpg format. What can I do?
Content-Type
header in the response.