apache 如何将.htaccess更新为有条件的动态gzip

mlnl4t2r  于 2023-10-23  发布在  Apache
关注(0)|答案(1)|浏览(140)

注意事项

有人认为这是How to serve precompressed gzip/brotli files with .htaccess的复制品。该问题仅寻求提供预压缩文件。这个问题是不同的。请参见下文。

我的目标

我想提供预压缩的brotli文件时,他们存在。如果不存在预压缩的brotli文件,则回退到on-the-flygzip-compression。

当前编码

我正在处理一个已经从.htaccess文件中启用了动态gzip的网站,如下所示:

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

修改代码

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

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

问题

这在brotli编码的文件按预期存在时提供。然而,我现在面临的问题是,因为剩余的资产在构建时没有进行brotli编码,所以现在没有对它们进行压缩。
我一直无法弄清楚如何使用gzip后备来为brotli提供服务,而不需要为gzip输出进行预压缩。
任何帮助都是赞赏的,谢谢!

pobjuy32

pobjuy321#

你的问题是你已经用静态的gzip配置替换了动态的gzip配置。
您需要将这两个配置都准备好,还需要更改Brotli代码,将环境设置为no-gzip,这样它就不会回退。下面的工作应该是;

  1. <ifmodule mod_deflate.c>
  2. AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml...
  3. </ifmodule>
  4. <IfModule mod_headers.c>
  5. # Serve brotli compressed CSS and JS files if they exist
  6. # and the client accepts brotli.
  7. RewriteCond "%{HTTP:Accept-encoding}" "br"
  8. RewriteCond "%{REQUEST_FILENAME}\.br" "-s"
  9. RewriteRule "^(.*)\.(js|css)" "$1.$2.br" [QSA]
  10. # Serve correct content types, and prevent double compression.
  11. RewriteRule "\.css\.br$" "-" [T=text/css,E=no-gzip:1]
  12. RewriteRule "\.js\.br$" "-" [T=text/javascript,E=no-gzip:1]
  13. <FilesMatch "(\.js\.br|\.css\.br)$">
  14. # Serve correct encoding type.
  15. Header append Content-Encoding br
  16. # Force proxies to cache brotli &
  17. # non-brotli css/js files separately.
  18. Header append Vary Accept-Encoding
  19. </FilesMatch>
  20. </IfModule>
展开查看全部

相关问题