2

笔记

有人建议这是How to serve precompressed gzip/brotli files with .htaccess的副本。该问题仅旨在提供预压缩文件。这个问题不一样。请看下文。

我的目标

我想在它们存在时提供预压缩的 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 提供服务。

任何帮助表示赞赏,谢谢!

4

1 回答 1

2

您的问题是您已经用静态替换了动态 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>
于 2019-09-30T18:57:14.650 回答