为什么文件大小对于apache命令Header附加Vary User-Agent来触发?

时间:2015-12-29 05:50:43

标签: apache .htaccess mod-deflate mod-headers vary

我正在使用symfony 3,并拥有以下.htaccess文件(附在此消息的最底部,标记为'问题.htaccess' )。我使用网站gtmetrix.com(使用pagespeed)来优化我的网站,但我的.css和.js文件出现以下错误。

Specify a Vary: Accept-Encoding header  
F (33)
    SERVER  HIGH
What's this mean?
The following publicly cacheable, compressible resources should have a "Vary: Accept-Encoding" header:

http://{{my website here}}/css/main.css
http://{{my website here}}/js/main.js

在您提及之前,它显示Header append Vary User-Agent显然没有说接受编码..

1。)(我已经查看了How to Specify "Vary: Accept-Encoding" header in .htaccess),其中讨论了如何设置它。

2。)我列出的代码在同一台服务器上的另一个网站上工作,我没有收到编码错误消息。,这意味着我的代码应该已经工作了(并且其他网站也有main.css和main.js)。 htaccess文件的唯一区别是它适用于SLIM框架而不是symfony,因此它看起来如下所示:

SLIM FRAMEWORK(其他网站.HTACCESS)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

AddType application/x-font-ttf .ttf

Header unset Pragma
FileETag None
Header unset ETag 

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType font/ttf "access plus 1 year"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

Symfony 3 FRAMEWORK(问题.HTACCESS)

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/js "access 1 week"
ExpiresByType application/javascript "access 1 week"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by Apache
    RewriteCond %{HTTP:Authorization} .
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule ^ %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

# These rules need to be at the bottom!
# Make it aware of True Type Fonts for Web Fonts.
AddType application/x-font-ttf .ttf

Header unset Pragma
FileETag None
Header unset ETag 

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

  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/js
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

问题是: symfony框架或他们的.htaccess文件有什么不同,不允许我使用Header append Vary User-Agent命令?

更新

因此,在做了一些实验后,我将symfony的.htaccess文件修改为与slims相同,我唯一的区别就是将一行DirectoryIndex app.php添加到slims .htaccess文件然后告诉它重写到app.php而不是index.php,但仍然存在错误。这告诉我它可能不是htaccess文件,但也许是我创建资产的方式?

在代码中,它在TWIG模板中看起来像这样。

{% spaceless %}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
            <link href="{{ asset('css/main.css') }}" rel="stylesheet" />
        {% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
    <body>
        {% block body %}{% endblock %}
        {% block javascripts %}
            <script src="{{ asset('js/main.js') }}"></script>
        {% endblock %}
    </body>
</html>
{% endspaceless %}

也许是因为我使用资产在引擎中以某种方式对该资源的编码器做了些什么?我不确定它会怎么做,但不知道还能在何处寻找。

更新#2

Ok在这个谜团中取得了很大的进展,我得到了变化编码的消息,但我不能完全确定原因,但我知道main.css文件的文件大小很重要。

当main.css具有以下内容时,它将无法指定vary:accept编码标头?也许是因为它太小而不能首先压缩?

.someclass{color:red;}.heythere{color:blue;}.heythereagain{color:blue;width:200px}.heytheretwice{color:green;height:50px;}

但是请给它以下main.css内容,并且消息在gtmetrix上消失。

a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before,q:after,q:before{content:'';content:none}table{border-collapse:collapse;border-spacing:0}.red{background-color:rgba(255,0,0,.75)}.blue{background-color:rgba(0,0,255,.75)}.green{background-color:rgba(0,255,0,.75)}.purple{background-color:rgba(255,0,255,.75)}.orange{background-color:rgba(255,150,0,.75)}.yellow{background-color:rgba(255,255,0,.75)}.black{background-color:rgba(0,0,0,.75)}.hide{display:none}.inline_block_fix:before{display:inline-block;content:'';height:100%;width:0;vertical-align:middle}.vertical_align{vertical-align:middle;display:inline-block;height:100%;width:0}.header{height:70px;color:#FFF;background-color:#2c3e50;font-size:16px;text-align:right;font-family:ProximaNova;text-align:center}.header a{color:#fff;text-decoration:none}.header .fa-phone{color:#42c044;padding-left:10px;padding-right:10px;font-size:24px!important;vertical-align:middle}.mobile_menu{display:inline-block;vertical-align:middle;font-size:24px!important;padding-right:10px;cursor:pointer}.phonebox{display:inline-block;vertical-align:middle;margin-right:0;border-radius:10px 10px 10px 10px;-moz-border-radius:10px 10px 10px 10px;-webkit-border-radius:10px 10px 10px 10px;border:0 solid #000;background-color:#42c044;height:41px;width:210px;font-size:26px;font-weight:700;text-align:center}.phonebox .phonetext{display:inline-block;vertical-align:middle}.callustext{display:none;vertical-align:middle}@media all and (min-width:600px){.callustext{display:inline-block}.mobile_menu{display:none!important}.header{text-align:right}.phonebox{margin-right:40px}}.footer{background-color:#2c3e50;text-align:center;font-family:ProximaNova;color:#fff;padding-top:30px}.footer .copyright_area{height:60px;line-height:60px;background-color:#33383c;color:#aaa;font-size:12px;margin-top:30px}.footer .copyright_area .copyright_links{padding-left:20px}.footer .copyright_area .copyright_links a{color:#aaa;padding-left:2px;padding-right:2px}.footer .whitebox{display:inline-block;vertical-align:middle;margin-left:20px;margin-right:20px;padding-top:20px;padding-bottom:15px;padding-left:30px;padding-right:30px;background-color:#fff;border-radius:5px;text-align:center}.footer .whitebox .footer_logo{display:inline-block;background-image:url(/images/logo-hires-opt.png);background-repeat:no-repeat;background-position:top;background-attachment:scroll;background-size:196px 75px;height:95px;width:196px}.footer .whitebox .bar{border-bottom:2px solid #485867;margin-bottom:20px}.footer .whitebox .asp{display:inline-block;background-image:url(/images/asp-opt.jpg);background-size:95px 75px;background-repeat:no-repeat;height:75px;width:95px}.footer .whitebox .cpo{display:inline-block;background-image:url(/images/cpo-opt.jpg);background-size:75px 75px;background-repeat:no-repeat;background-position:center;height:75px;width:100px}.footer .links_area{display:inline-block;vertical-align:middle;text-align:left;font-size:18px;margin-left:20px;margin-right:20px;width:285px;margin-top:30px}.footer .links_area .links_area_title{font-size:28px;font-weight:700;margin-bottom:20px}.footer .links_area ul li{margin-left:10px;margin-top:10px}.footer .links_area ul li i{width:10px;margin-right:20px}.footer .links_area a{color:#fff;text-decoration:none;border-bottom:2px solid #777F88}@font-face{font-family:ProximaNova;src:url(/fonts/proximanova-regular-webfont.ttf)}@font-face{font-family:ProximaNovaAltBold;src:url(/fonts/proxima_nova_alt_bold-webfont.ttf)}

我仍然在javascript上有错误,但我会继续在我的javascript文件中添加随机函数,看看是否会导致错误消失。目前我的JS文件是:

function test(){alert('test');}function test2(){alert('test2');function test3(){alert('test3');alert('another test');}}

更新#3:

确实文件大小是罪魁祸首,将我的js文件更改为..

function test(){alert('test');}function test2(){alert('test2');}function test3(){alert('test3');alert('another test');}function test4(){alert('test4');alert('another test4');}function test5(){alert('test5');alert('another test5');}function test6(){alert('test6');alert('another test6');}function test7(){alert('test7');alert('another test7');}function test8(){alert('test8');alert('another test8');}function test9(){alert('test9');alert('another test9');}function test10(){alert('test10');alert('another test10');}function test11(){alert('test11');alert('another test11');}function test12(){alert('test12');alert('another test12');}function test13(){alert('test13');alert('another test13');}function test14(){alert('test14');alert('another test14');}function test15(){alert('test15');alert('another test15');}function test16(){alert('test16');alert('another test16');}function test17(){alert('test17');alert('another test17');}function test18(){alert('test18');alert('another test18');}function test19(){alert('test19');alert('another test19');}function test20(){alert('test20');alert('another test20');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');alert('hello');}

足以使标题变化编码错误消失。

更新#4

正在阅读此页面(https://www.fastly.com/blog/best-practices-for-using-the-vary-header),显然如果您正在使用mod_deflate,则会自动将正确的Vary标头添加到您的回复中。因此,当main.css和main.js文件较小时,mod_deflate很可能会覆盖我建议的更改。

所以新问题:

为什么尝试添加Header append Vary User-Agent命令时文件大小很重要?在这种情况下,我应该忽略gtmetrix(pagespeed)的速度优化建议吗?或者如果mod_deflate被覆盖,这甚至是一个问题吗?如果是这样,我如何修复mod_deflate导致的标题的覆盖?

1 个答案:

答案 0 :(得分:0)

经过大量研究和审议后,我得出的结论是,mod_deflate是罪魁祸首。

根据apache的自我:http://httpd.apache.org/docs/2.2/mod/mod_deflate.html

mod_deflate模块发送Vary:Accept-Encoding HTTP响应头,以警告代理缓存响应应仅发送给发送相应Accept-Encoding请求头的客户端。 这可以防止压缩内容被发送到不理解它的客户端。

这里的关键是理解压缩是如何工作的。例如,当您从用户浏览器查看HTTP请求时,您可能会看到这一点。 (使用google chromes督察或Firefox的firebug来查看这些内容)。

GET /css/main.css HTTP/1.1
Host: dev.yoursitehere.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Referer: http://dev.yoursitehere.com
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,nb;q=0.6
Cookie: PHPSESSID=2fd616076481f661975f7de2a92a0016

注意这一行:接受编码:gzip,deflate,sdch

这是对服务器的说法,如果你把它们发回给我,我可以解压缩gzip,deflate和sdch压缩格式。

服务器不必发回压缩结果。事实上,当文件大小很小时,这就是我的情况。

8096字节是apache deflate moduels设置的默认值 DeflateBufferSize

这意味着如果您想要服务器的内容大于8096字节,那么它将压缩结果,并且根据我的.htaccess文件,我使用 DEFLATE 压缩方法。

只有文件大小足够大,我才注意到响应标题看起来像这样。

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 29 Dec 2015 20:25:28 GMT
Content-Type: text/css
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Last-Modified: Tue, 29 Dec 2015 19:31:30 GMT
Cache-Control: max-age=2592000
Expires: Thu, 28 Jan 2016 20:25:28 GMT
Content-Encoding: gzip

正常情况下,当main.css或main.js文件的文件大小很小时,Vary:Accept-Encoding响应头不存在,但是一旦超过了值,压缩变换头的数量就会自动由mod_deflate模块添加。

该标头告诉chrome这不是正常的未压缩文件,而是需要解压缩的文件。在这种特殊情况下,内容编码设置为gzip。这意味着它会在发回给我之前压缩结果。

https://en.wikipedia.org/wiki/Gzip

根据这个,gzip使用DEFLATE算法(我的浏览器说它可以在我的请求标题中处理 Accept-Encoding:gzip,deflate,sdch

因此浏览器能够正确地重建它。

这就是为什么文件大小在附加vary头之前很重要的原因,以及vary头在这个上下文中实际意味着什么。