大网数据广告活动
服务器运维问答

htaccess rewrite /dir/*.jpg to /dir/webp/*.webp only when webp file exists

· 52CE 我爱测

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 subd…

问题原文

原帖链接 · Diego Flores · CC BY-SA 4.0

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:

  1. Only matches PNG/JPG/GIF file
  2. Original images dir pattern is: /site/views/00_projects/[VARIABLE MAIN DIR NAME HERE]/content/image/[VARIABLE SUBDIR NAME HERE]/*.jpg
  3. New *.webp dir is pattern is: /site/views/00_projects/[VARIABLE DIR NAME HERE]/content/image/[VARIABLE SUBDIR NAME HERE]/webp/*.webp
  4. Only rewrite IF webp file exists

I really have no idea on how to make it work. Can someone help?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

Strictly speaking you also need to make sure the user-agent making the request supports WEBP images (ie. check the Accept HTTP request header for image/webp).

Try the following near the top of the root .htaccess file:

RewriteEngine On

# Rewrite images to WebP if they exist
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1/webp/$2.webp -f
RewriteRule ^(site/views/00_projects/[^/]+/content/image/[^/]+)/([^/]+)\.(?:png|jpg|gif)$ $1/webp/$2.webp [T=image/webp,L]

The RewriteRule pattern (ie. ^(site/views/00_projects/[^/]+/content/image/[^/]+)/([^/]+)\.(?:png|jpg|gif)$) matches the requested png, jpg or gif image and saves the URL-path in the $1 backreference and the filename in the $2 backreference (used later in the RewriteRule substitution string).

The first condition (RewriteCond directive) that checks against the HTTP_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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-07-24)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。