我正在开发一个继承的网站,并且正在查看 .htaccess
文件。说实话,我真的不熟悉编写自定义 .htaccess
规则,所以我想知道是否有人可以向我解释这段代码片段中发生了什么?
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
</IfModule>
经过一些谷歌搜索后,我很确定它会获取任何提供的图像并在最后返回 webp 而不是其原始扩展名?
我相信代码的目的是欺骗页面速度洞察,以便它不会提示提供下一代图像格式。
我只是想知道是否有人可以给我一个完整的详细说明到底发生了什么以及它是如何工作的?
此外,我注意到,当我更改网站上的图像大小(出于优化目的)时,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?
基本上是的。 (尽管,这不是“重定向”。)
更具体地说...(提供 mod_rewrite 已启用 - 由外部 <IfModule mod_rewrite.c>
容器检查):
-
RewriteRule (.+)\.(jpe?g|png)$
- 对于每个与正则表达式(.+)\.(jpe?g|png)$
匹配的 URL 路径。换句话说,任何以.jpg
结尾的 URL ,.jpeg
或.png
. -
RewriteCond %{HTTP_ACCEPT} image/webp
- 还有Accept
HTTP 请求 header 包含字符串image/webp
。换句话说,用户代理接受 webp 图像。 -
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
- 以及相应的.webp
图像与请求的文件位于同一位置。例如。请求/foo/bar/baz.jpg
和/foo/bar/baz.webp
存在。 -
RewriteRule -------- $1.webp
- 然后内部重写将请求发送到.webp
图像(例如foo/bar/baz.webp
)。请注意,这不是“重定向”,用户代理仍然看到原始的.jpg
(或.png
)文件名。还...-
T=image/webp
- 设置Content-Type
标题为image/webp
。 (覆盖否则会发送的image/jpeg
或image/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.
我认为其目的不一定是“愚弄页面速度见解”。 (仅仅为了欺骗一个工具就需要做很多工作!)
但是,它确实允许优雅降级...a .jpg
默认情况下提供服务,.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
图像(或者它本来就不存在),那么任何合规的用户代理都不会看到图像中的更改。
future ...当一切、所有人都支持.webp
图像,然后您可以安全地删除两个 RewriteCond
指令(以及相对昂贵的文件系统检查)。并将所有图像保存为 .webp
(您的网站上不存在 .jpg
图像)。图像URL仍然是 .jpg
。这些指令允许您升级图像而无需更改 URL。
在这种情况下,您还应该删除 <IfModule mod_rewrite.c>
包装器,因为您的网站现在依赖 mod_rewrite 来完成它的工作。 <IfModule>
仅当 mod_rewrite 对于您的网站“正常”工作而言是可选时,才应使用包装器。
关于.htaccess - 代码片段说明,.htaccess 中的图像服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54331178/