I'm trying to rewrite all website files (*.jpg|*.gif|*.png
) to *.webp
in a subdir, but only when the *.webp
file exists. Previous and new files have the same name, only changing the extension and *.webp
files are all under subdir of the original one.
I'm struggling with htaccess to do the job. Basic rules are:
- Only matches PNG/JPG/GIF file
- Original images dir pattern is:
/site/views/00_projects/[VARIABLE MAIN DIR NAME HERE]/content/image/[VARIABLE SUBDIR NAME HERE]/*.jpg
- New
*.webp
dir is pattern is:/site/views/00_projects/[VARIABLE DIR NAME HERE]/content/image/[VARIABLE SUBDIR NAME HERE]/webp/*.webp
- Only rewrite IF webp file exists
I really have no idea on how to make it work. Can someone help?
Strictly speaking you also need to make sure the user-agent making the request supports WEBP images (ie. check the
Accept
HTTP request header forimage/webp
).Try the following near the top of the root
.htaccess
file:The
RewriteRule
pattern (ie.^(site/views/00_projects/[^/]+/content/image/[^/]+)/([^/]+)\.(?:png|jpg|gif)$
) matches the requestedpng
,jpg
orgif
image and saves the URL-path in the$1
backreference and the filename in the$2
backreference (used later in theRewriteRule
substitution string).The first condition (
RewriteCond
directive) that checks against theHTTP_ACCEPT
server variable, checks that the user-agent supports WEBP images.The second condition checks that the target webp image exists.
The
T=image/webp
flag is necessary to send the correct mime-type (Content-Type
header) back to the client.