如何使用 HTTP 标头缓存动态 CSS


How can I cache dynamic CSS with HTTP headers?

这是这个问题的直接重复,但提供的解决方案不起作用。

作为我维护的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 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

如果您希望浏览器缓存文件,则应将 Cache-control 标头设置为 public:

header('Cache-control: public');