【问题标题】:How can I cache dynamic CSS with HTTP headers?如何缓存带有 HTTP 标头的动态 CSS?
【发布时间】:2014-03-31 07:57:32
【问题描述】:

这是this question 的直接复制品,但提供的解决方案不起作用。

作为我维护的 WordPress 插件的一部分,我目前正在使用以下代码生成一个动态 CSS 文件:

public static function buildCustomCss() {
  if (1 == intval(get_query_var(self::$query_var))) {
     ob_start();
        global $css;
        $expires = 60 * 60 * 24 * 365; // cache for a year

        header('Pragma: public');
        header('Cache-Control: maxage=' . $expires);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
        header('Content-type: text/css');

        echo str_replace('>', '>', esc_html($css));
     ob_end_flush();
     exit;
  }
}

使用的标头值与上面引用的问题中使用的匹配,但 Chrome AND Firefox 都拒绝接受缓存请求。我尝试了多台服务器,每台服务器每次都返回一个200 响应。我希望这会被证明是一个比仅仅将 CSS 放入主页更好的解决方案,但如果我不能让缓存工作,那么它最终会变得更糟。

请求标头的完整列表(Chrome):

Accept:text/css,*/*;q=0.1
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:<cookie values>
DNT:1
Host:example.org
Referer:http://example.org/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36

响应头的完整列表(已编辑以包含最新的测试头,包括pragmacache-control 中的public):

Cache-Control:no-transform,public,maxage=31536000
Connection:keep-alive
Content-Type:text/css; charset=UTF-8
Date:Sun, 30 Mar 2014 22:55:57 GMT
Expires:Mon, 30 Mar 2015 22:55:56 GMT
Pragma:public
Server:nginx
Transfer-Encoding:chunked

【问题讨论】:

    标签: php css wordpress caching dynamic-css


    【解决方案1】:

    如果你想让一个文件被浏览器缓存,你应该将 Cache-control 头设置为 public:

    header('Cache-control: public');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2011-01-24
    • 2013-07-17
    • 2011-12-24
    • 2016-06-29
    相关资源
    最近更新 更多