1

我正在摆弄 PageSpeed Insights,它引导我将 Webpack 中的 css 和 js 文件压缩为 .br(用 Brotli 压缩)和 .gz(用 gzip 压缩),以便将它们提供给接受它们的浏览器。.htaccess 做出决定。

由于 .htaccess 做出决定,我不得不使用AddTypeclose。由于 .htaccess 不适用于多扩展名文件名,因此我必须创建一个自定义扩展名,即cssbrcssgz和. 在 .htaccess 中,它们被识别得很好:jsbrjsgz

AddEncoding gzip .jsgz .cssgz
AddType application/javascript .jsgz
AddType text/css .cssgz

AddEncoding br .jsbr .cssbr
AddType application/javascript .jsbr
AddType text/css .cssbr

这通常有效。对于无法使用压缩文件的浏览器,纯 css 和 js 也有回退。当我进行更改并使用 webpack 更新文件时,一切正常。但是当我结帐到另一个分支并合并时,git 认为我的自定义文件没有改变。.css并按.js预期工作,但对于.cssbr浏览器通知我它无法解码的文件(ERROR_CONTENT_DECODING_FAILED)。我需要做的是再次运行 webpack 并且它可以在本地运行,但是 git 不会提交更改,因为文件似乎没有改变。我尝试删除它们并阅读。

TL;博士:

我有在切换分支或提交时被认为未更改的自定义文件。
我可以从另一个角度寻求解决方案,例如将它们更改为不同的扩展名,但是如何使 .htaccess 与它们一起使用呢?

.htaccess 供参考:

<IfModule mod_headers.c>
  # Serve brotli compressed CSS files if they exist and the client accepts br.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteRule ^(.*)assets/frontend/(.*)\.css $1assets/frontend/$2.cssbr [QSA,L,T=text/css,E=no-gzip:1]

  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteRule ^(.*)assets/frontend/(.*)\.css $1assets/frontend/$2.cssgz [QSA,L,T=text/css,E=no-gzip:1]

  # Serve brotli compressed JS files if they exist and the client accepts br.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteRule ^(.*)assets/frontend/(.*)\.js $1assets/frontend/$2.jsbr [QSA,L,T=text/javascript,E=no-gzip:1]

  # Serve gzip compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteRule ^(.*)assets/frontend/(.*)\.js $1assets/frontend/$2.jsgz [QSA,L,T=text/javascript,E=no-gzip:1]

  # Serve correct content types, and prevent mod_deflate double gzip.
  RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
  RewriteRule \.css\.br$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.br$ - [T=text/javascript,E=no-gzip:1]

  <FilesMatch "(\.js\.gz|\.css\.gz)$">
    # Serve correct encoding type.
    Header set Content-Encoding gzip
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
  <FilesMatch "(\.js\.br|\.css\.br)$">
    # Serve correct encoding type.
    Header set Content-Encoding br
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
</IfModule>

附加信息:根据 PageSpeed Insights 的说法,我使用 webpack 压缩文件,因为在服务器上这样做会增加时间并破坏使用压缩的目的

4

1 回答 1

2

我找到了解决方案。问题确实出在 git 中,但出在换行符上。

我在 Windows 上,所以 git 将 CRLF 更改为 LF,因为它们是二进制文件,所以会破坏文件。我需要做的是将它们添加为二进制文件,.gitattributes如下所示:

*.cssbr binary
*.cssgz binary
*.jsbr binary
*.jsgz binary
于 2020-07-21T13:55:11.187 回答