81

Google PageSpeed 说我应该为 JS 和 CSS “指定一个 Vary:Accept-Encoding 标头”。如何在 .htaccess 中执行此操作?

4

7 回答 7

90

我猜这意味着您为您的 css 和 js 文件启用 gzip 压缩,因为这将使客户端能够接收 gzip 编码的内容和纯内容。

这是在 apache2 中的操作方法:

<IfModule mod_deflate.c>
    #The following line is enough for .js and .css
    AddOutputFilter DEFLATE js css

    #The following line also enables compression by file content type, for the following list of Content-Type:s
    AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml

    #The following lines are to avoid bugs with some browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html 
</IfModule>

以下是添加Vary Accept-Encoding标题的方法:[src]

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

Vary:头告诉该 url 提供的内容将根据某个请求标头的值而变化。这里它说它将为说他们Accept-Encoding: gzip, deflate(请求标头)的客户提供不同的内容,而不是为不发送此标头的客户提供的内容。AFAIK 的主要优点是让中间缓存代理知道由于这种更改,它们需要具有相同 url 的两个不同版本。

于 2010-09-04T06:51:39.867 回答
4

恐怕 Aularon 没有提供足够的步骤来完成这个过程。通过一些试验和错误,我能够在我的专用 WHM 服务器上成功启用 Gzipping。

以下是步骤:

  • 在 WHM 中运行 EasyApache,在 Exhaustive Options 列表中选择 Deflate,然后重建服务器。

  • 完成后,转到 Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include,选择 All Versions,然后将 mod_headers.c 和 mod_headers.c 代码(在 Aularon 的帖子中列出)粘贴到另一个上面输入字段。

  • 保存后,我看到平均节省了 75.36% 的数据!您可以使用此 HTTP 压缩工具运行前后测试以查看您自己的结果: http: //www.whatsmyip.org/http_compression/

希望这对你们所有人都有效!

  • 马特
于 2011-08-18T22:53:17.233 回答
3

也可以压缩你的字体文件!

add "x-font/otf x-font/ttf x-font/eot"

如:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot
于 2012-08-01T18:21:30.683 回答
1

这让我发疯,但似乎 aularon 的编辑在"Vary". 所以改变"Vary Accept-Encoding""Vary: Accept-Encoding"我解决了这个问题。

我会在帖子下面发表评论,但它似乎不会让我这样做。

无论如何,我希望这可以避免我遇到同样的麻烦。

于 2012-06-21T19:51:09.923 回答
1

如果有人需要这个NGINX配置文件,这里是片段:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}
于 2016-08-17T08:09:58.657 回答
1

花了很多时间来澄清那是什么。请阅读这篇文章以获取高级.HTACCESS代码并了解它们的作用。

您可以使用:

Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"
于 2016-08-22T19:33:38.707 回答
0

无需指定甚至检查文件是否已压缩,您可以在每个请求时将其发送到每个文件。

它告诉下游代理如何匹配未来的请求标头,以决定是否可以使用缓存的响应,而不是从源服务器请求新的响应。

<ifModule mod_headers.c>
  Header unset Vary
  Header set Vary "Accept-Encoding, X-HTTP-Method-Override, X-Forwarded-For, Remote-Address, X-Real-IP, X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port, X-Forwarded-Server"
</ifModule>
  • unset是可选地修复旧版 GoDaddy 主机中的一些错误。
于 2016-01-13T04:30:42.907 回答