7

我试图为 html、js 和 css 提供预压缩的 gzip/brotli 文件。使用以下代码。

RewriteEngine on

    # Brotli
    # If the web browser accept brotli encoding… 
    RewriteCond %{HTTP:Accept-encoding} br
    # …and the web browser is fetching a probably pre-compressed file…
    RewriteCond %{REQUEST_URI} .*\.(css|html|js)
    # …and a matching pre-compressed file exists… 
    RewriteCond %{REQUEST_FILENAME}.br -s
    # …then rewrite the request to deliver the brotli file
    RewriteRule ^(.+) $1.br
    # For each file format set the correct mime type (otherwise brotli mime type is returned) and prevent Apache for recompressing the files
    RewriteRule "\.css\.br$" "-" [T=text/css,E=no-brotli,E=no-gzip]
    RewriteRule "\.html\.br$" "-" [T=text/html,E=no-brotli,E=no-gzip]
    RewriteRule "\.js\.br$" "-" [T=application/javascript,E=no-brotli,E=no-gzip]

    # Gzip
    # If the web browser accept gzip encoding… 
    RewriteCond %{HTTP:Accept-Encoding} gzip
    # …and the web browser is fetching a probably pre-compressed file…
    RewriteCond %{REQUEST_URI} .*\.(css|html|js)
    # …and a matching pre-compressed file exists… 
    RewriteCond %{REQUEST_FILENAME}.gz -s
    # …then rewrite the request to deliver the gzip file
    RewriteRule ^(.+) $1.gz
    # For each file format set the correct mime type (otherwise gzip mime type is returned) and prevent Apache for recompressing the files
    RewriteRule "\.css\.gz$" "-" [T=text/css,E=no-brotli,E=no-gzip]
    RewriteRule "\.html\.gz$" "-" [T=text/html,E=no-brotli,E=no-gzip]
    RewriteRule "\.js\.gz$" "-" [T=application/javascript,E=no-brotli,E=no-gzip]

    <FilesMatch "\.(css|html|js)\.br$">
        # Prevent mime module to set brazilian language header (because the file ends with .br)
        RemoveLanguage .br
        # Set the correct encoding type
        Header set Content-Encoding br
        # Force proxies to cache brotli & non-brotli files separately
        Header append Vary Accept-Encoding
    </FilesMatch>
    <FilesMatch "\.(css|html|js)\.gz$">
        # Serve correct encoding type
        Header set Content-Encoding gzip
        # Force proxies to cache gzip & non-gzip files separately
        Header append Vary Accept-Encoding
    </FilesMatch>

我的文件夹结构如下所示:

  • .htaccess
  • 索引.php
  • /css/
  • /css/main.css
  • /css/main.css.gz
  • /css/main.css.br

但是我在使用上面的代码时得到 404s。

4

3 回答 3

5

设置 RewriteBase 修复了它。

RewriteBase /
于 2017-09-29T13:04:53.423 回答
1

写这个来帮助别人。我必须添加%{DOCUMENT_ROOT}RewriteCond才能让它工作。

本质上,将所有更改RewriteCond

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}\.br -s
于 2019-10-04T12:38:35.310 回答
0

对我来说,问题是 http 连接不支持 brotli 压缩。请参阅为什么 HTTP 不支持 Brotli?

于 2022-02-26T17:07:09.913 回答