谷歌页面速度建议我在JS和CSS中“指定 Vary: Accept-Encoding头部信息”。我该如何在 .htaccess 文件中实现此功能?
我猜这意味着你要为你的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
标头的客户端提供不同的内容,而对于没有发送此标头的客户端则提供其他内容。我所知道的主要优点是让中间缓存代理知道它们需要针对此更改为同一URL维护两个不同版本。
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
如果有人需要用于 NGINX
配置文件的代码段,这里是示例:
location ~* \.(js|css|xml|gz)$ {
add_header Vary "Accept-Encoding";
(... other headers or rules ...)
}
.HTACCESS
代码,并了解它们的作用。Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"
"Vary"
后面缺少了冒号。所以将"Vary Accept-Encoding"
更改为"Vary: Accept-Encoding"
解决了我的问题。无需指定或检查文件是否已压缩,您可以将其发送到每个文件,每个请求都可以。
它告诉下游代理如何匹配未来的请求头以决定是否可以使用缓存响应而不是从源服务器请求新的响应。
<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 托管中的错误,可选。
Vary: Accept-Encoding
将告诉浏览器根据Content-Encoding
头文件在缓存中存储页面的版本。您可以查看 https://dev59.com/53I-5IYBdhLWcg3wMFS0 和 https://developers.google.com/speed/docs/best-practices/caching?hl=sv&csw=1#LeverageProxyCaching - Ismael MiguelAccept-Encoding
请求头值的每个变体不同,而不是服务器响应头值的每个Content-Encoding
变体。 - aularon