代码片段解释,.htaccess 中的图像服务

Code snippet explanation, image serving in .htaccess

我正在我继承的网站上工作,我正在查看 .htaccess 文件。说实话,我真的不熟悉编写自定义 .htaccess 规则,所以我想知道是否有人可以向我解释这段代码片段中发生了什么?

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_ACCEPT} image/webp
  RewriteCond %{DOCUMENT_ROOT}/.webp -f
  RewriteRule (.+)\.(jpe?g|png)$ .webp [T=image/webp,E=accept:1]
</IfModule>

在进行一些谷歌搜索后,我很确定它会拍摄任何提供的图像并在最后返回 webp 而不是其原始扩展名?

我相信代码的目的是愚弄 pagespeed 洞察力,这样它就不会抱怨提供下一代图像格式。

我只是想知道是否有人可以向我详细说明到底发生了什么以及它是如何工作的?

此外,我注意到当我在网站上更改图像大小(出于优化目的)时,pagespeed 不会记录更改,而此代码存在于 htaccess 中,例如它有助于某种图片缓存?如果我删除此代码段,pagespeed 会检测到新的优化图像吗?

i'm pretty sure its taking any image thats served up and returning with webp on the end instead of its original extension?

基本上是的。 (虽然,这不是 "redirect"。)

更具体地说...(提供 mod_rewrite 已启用 - 由外部 <IfModule mod_rewrite.c> 容器检查):

  1. RewriteRule (.+)\.(jpe?g|png)$ - 对于每一个匹配正则表达式 (.+)\.(jpe?g|png)$ 的 URL-path。换句话说,任何以 .jpg.jpeg.png.
  2. 结尾的 URL
  3. RewriteCond %{HTTP_ACCEPT} image/webp - Accept HTTP 请求 header 包含字符串 image/webp。换句话说 user-agent 接受 webp 图片。
  4. RewriteCond %{DOCUMENT_ROOT}/.webp -f - 相应的 .webp 图像与请求的文件存在于同一位置。例如。请求 /foo/bar/baz.jpg/foo/bar/baz.webp 存在。
  5. RewriteRule -------- .webp - 然后内部重写.webp图像的请求(例如foo/bar/baz.webp)。请注意,这不是 "redirect",user-agent 仍然会看到原始的 .jpg(或 .png)文件名。还...
    • T=image/webp - 将 Content-Type header 设置为 image/webp。 (覆盖本应发送的 image/jpegimage/png 值。)
    • E=accept:1 - 将 环境变量 accept 设置为 1。(然后您的应用程序可以使用它。)

I believe the intent of the code is to fool pagespeed insights so that it doesnt complain about serving next gen image formats.

我认为其意图不一定是“fool pagespeed insights”。 (仅仅为了欺骗一个工具,就需要做很多工作!)

但是,它确实允许优雅降级...默认情况下提供 .jpg,如果 user-agent 则提供 .webp支持它(它存在!)。

Also, i've noticed that when I do change image sizes on the site (for optimisation purposes), pagespeed doesn't register the changes whilst this code is present in the htaccess, like its contributing to some sort of image cache? If I remove this snippet, pagespeed detects the new optimised images?

您要重新生成 .webp 图像吗?

此代码仅在请求 .jpg(或 .png)张图片并且存在相应的 .webp 张图片时适用。除非您还更新 .webp 图片(或者它本来就不存在),否则任何合规的 user-agent 都不会看到您的图片发生变化。


将来...当所有人都支持 .webp 图像时,您可以安全地删除两个 RewriteCond 指令(以及相对昂贵的文件系统检查)。并将所有图片保存为 .webp(您的网站上不存在 .jpg 图片)。图片 URL 仍然是 .jpg。这些指令允许您升级图像而无需更改 URL.

在这种情况下,您还应该删除 <IfModule mod_rewrite.c> 包装器,因为您的站点现在 依赖 mod_rewrite 做它的事情。 <IfModule> 包装器仅应在 mod_rewrite 对您的站点工作 "normally".

可选 时使用