如何更新.htaccess文件以条件性地实时压缩gzip?

3

注意

有人建议这是如何使用.htaccess服务预压缩的gzip / brotli文件的重复问题。那个问题仅寻求提供预先压缩的文件。这个问题是不同的,请参见下文。

我的目标

当预先压缩的brotli文件存在时,我希望能够提供服务。如果不存在预先压缩的brotli文件,则降级为实时gzip压缩。

当前代码

我正在处理一个已经启用实时gzip的站点,其 .htaccess 文件如下:

<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备用的brotli而不需要我针对gzip输出进行预压缩。

感谢您的任何帮助!


似乎不是重复问题。您链接的问题旨在为所有请求的文件提供预压缩版本。我的问题旨在在请求的文件没有预压缩的brotli等效文件时回退到即时gzip文件。 - jpodwys
@BarryPollard 请重新阅读问题并删除关闭重复的投票。 - jpodwys
完成。你不想使用Brotli作为后备方案吗?如果预压缩不存在的话,有什么原因呢? - Barry Pollard
谢谢!Brotli 比 gzip 要慢得多,我不能保证未预压缩的资源完全静态,因此一旦它们被压缩,我就不能将它们缓存。这是一个较旧的系统,我正在采取渐进式的措施来改进它。 - jpodwys
好的。根据我的经验,除非你处理大文件或者高流量的网络服务器,否则它在网络服务器标准下不会明显变长。但是每个人都有自己的看法。 - Barry Pollard
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>

谢谢!我已经尝试了两个代码块,但我不知道no-gzip设置。这解决了问题! - jpodwys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接