如果UA请求,则使用mod_negotiation来提供webp

Ric*_*haw 7 apache mod-negotiation

如果浏览器支持它,是否可以使用mod_negotiation来提供webp图像,否则可以使用jpg?

例如,如果我链接到带有路径/ images/test的图像,如果UA知道webp,它会提供在/images/test.webp中找到的图像,否则为jpg?

我试过四处寻找,但似乎Chrome中的Accept标头至少看起来像Accept:*/*,而不是指定图像类型.

如果这不是这样做的,有人有任何其他建议吗?

小智 2

为了提供 WebP 图像,我在 nginx 中使用重写规则来检查文件是否存在以及对 WebP 图像的支持。由于OP提到了mod_negotiation,我将其移植到Apache mod_rewrite。重写会查找包含单词“chrome”的用户代理,然后检查扩展名为 .webp 且与 .jpg 或 .png 文件同名和路径的文件,如果是,则提供 WebP 文件。重写规则有点混乱,但它可以完成工作。

AddType image/webp .webp
# strip the extension off of all JPGs
RewriteCond %{HTTP_USER_AGENT} (chrome) [NC]
RewriteRule (.*)\.jpg$ $1

#check for a webp file, if so serve it
RewriteCond   %{REQUEST_FILENAME}.webp  -f
RewriteRule   (.*)  $1.webp [E=WEBP:1]

#check for if we did not have a webp file and we do have a jpg, if so serve it
RewriteCond   %{REQUEST_FILENAME}.jpg  -f
RewriteCond   %{REQUEST_FILENAME}.webp  !-f
RewriteRule   (.*)  $1.jpg

# strip the extension off of all PNGs
RewriteCond %{HTTP_USER_AGENT} (chrome) [NC]
RewriteRule (.*)\.png$ $1

#check for a webp file, if so serve it
RewriteCond   %{REQUEST_FILENAME}.webp  -f
RewriteRule   (.*)  $1.webp [E=WEBP:1]

#check for if we did not have a webp file and we do have a png, if so serve it
RewriteCond   %{REQUEST_FILENAME}.png  -f
RewriteCond   %{REQUEST_FILENAME}.webp  !-f
RewriteRule   (.*)  $1.png
Run Code Online (Sandbox Code Playgroud)

对于我的网站,在检测到浏览器对 WebP 的支持后,我可以通过 JavaScript 加载照片,而不是依赖用户代理字符串。如果存在 WebP 支持,那么我会在开始加载图像之前设置一个 cookie。因此代替这个 RewriteCond

RewriteCond %{HTTP_USER_AGENT} (chrome) [NC]
Run Code Online (Sandbox Code Playgroud)

我会用这个

RewriteCond %{HTTP_COOKIE} supports_webp
Run Code Online (Sandbox Code Playgroud)