我怎样才能即时更新 .htaccess 以有条件地 gzip



注意

有人建议这是如何使用.htaccess提供预压缩的gzip/brotli文件的副本。该问题仅寻求提供预压缩文件。这个问题是不同的。请看下文。

我的目标

我想在存在预压缩的 brotli 文件时提供它们。如果不存在预压缩的 brotli 文件,请回退到动态gzip 压缩。

当前代码

我正在一个已经从其.htaccess文件中启用了即时 gzip 的网站,如下所示:

<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml...
</ifmodule>

修改后的代码

我已经设置了一个构建脚本,它使用 brotli 压缩许多静态资产。为了服务它们,我将上面的mod_deflate块替换为以下内容:

<IfModule mod_headers.c>
# Serve brotli compressed CSS and JS files if they exist
# and the client accepts brotli.
RewriteCond "%{HTTP:Accept-encoding}" "br"
RewriteCond "%{REQUEST_FILENAME}.br" "-s"
RewriteRule "^(.*).(js|css)"              "$1.$2.br" [QSA]
# Serve correct content types, and prevent double compression.
RewriteRule ".css.br$" "-" [T=text/css,E=no-brotli:1]
RewriteRule ".js.br$"  "-" [T=text/javascript,E=no-brotli:1]
<FilesMatch "(.js.br|.css.br)$">
# Serve correct encoding type.
Header append Content-Encoding br
# Force proxies to cache brotli &
# non-brotli css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
</IfModule>

问题所在

这将在 brotli 编码文件按预期存在时提供这些文件。但是,我现在面临的问题是,由于剩余的资产在构建时未进行 brotli 编码,因此它们现在无需压缩即可提供。

我一直无法弄清楚如何使用不需要我预压缩 gzip 输出的 gzip 回退来提供 brotli。

任何帮助不胜感激,谢谢!

你的问题是你已经用静态替换了动态gzip配置。

您既需要配置位,还需要更改 Brotli 代码以将环境设置为no-gzip,这样它就不会回退。以下应该有效;

<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml...
</ifmodule>
<IfModule mod_headers.c>
# Serve brotli compressed CSS and JS files if they exist
# and the client accepts brotli.
RewriteCond "%{HTTP:Accept-encoding}" "br"
RewriteCond "%{REQUEST_FILENAME}.br" "-s"
RewriteRule "^(.*).(js|css)"              "$1.$2.br" [QSA]
# Serve correct content types, and prevent double compression.
RewriteRule ".css.br$" "-" [T=text/css,E=no-gzip:1]
RewriteRule ".js.br$"  "-" [T=text/javascript,E=no-gzip:1]
<FilesMatch "(.js.br|.css.br)$">
# Serve correct encoding type.
Header append Content-Encoding br
# Force proxies to cache brotli &
# non-brotli css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
</IfModule>

最新更新