如何在 Yii2 中打开 HTTP 缓存?

How do I turn on HTTP caching in Yii2?

我在控制器中设置了这些值,但它不起作用。

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
        'httpCache' => [
          'class' => 'yii\filters\HttpCache',
          'sessionCacheLimiter' => 'public',
          'cacheControlHeader' => 'public, max-age=3600',
        ],
    ];
}

http://www.yiiframework.com/doc-2.0/guide-caching-http.html#cache-control

$ curl -I http://localhost:81/xxxx/web/shopping/search?q=toaster
HTTP/1.1 200 OK
Date: Wed, 11 Nov 2015 08:58:57 GMT
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.2d PHP/5.6.12
X-Powered-By: PHP/5.6.12
Set-Cookie: PHPSESSID=t07qapiiv7crdkva14ojn6cvg5; path=/; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: search=4ef489ad7fa4567884eebc22279836f85acec05395053c863ed86c2679be9477a%3A2%3A%7Bi%3A0%3Bs%3A6%3A%22search%22%3Bi%3A1%3Bs%3A38%3A%22%2Fxxxx%2Fweb%2Fshopping%2Fsearch%3Fq%3Dtoaster%22%3B%7D; path=/; httponly
Set-Cookie: _csrf=72e0104d312d81ddde455cff7566d3d186e3b25f8f41fc03a1f4a533d9b739ada%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22R1HklhizymwcXPVxJkBCvNR2gBwInqdw%22%3B%7D; path=/; httponly
Content-Type: text/html; charset=UTF-8

由于问题没有答案,我刚刚更新了问题。我找到了 Yii 没有输出所有 headers 的原因,但我仍然不知道如何打开缓存。事实上,现在它正在使用 Cache-Control: no-cache 主动关闭缓存,即使我要求它打开。

即使有一个测试动作,它也会设置no-cache

$ curl -I http://localhost:81/xxxx/web/shopping/test
HTTP/1.1 200 OK
Set-Cookie: PHPSESSID=bvdnd33uu8qj0s88q2sr7n7696; path=/; HttpOnly
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
[...]
php.ini
$ grep cache_limiter  /etc/php5/php.ini
session.cache_limiter = nocache

我发现手动调用 session_cache_limiter 可以输出 Cache-Control,但不是我设置的值。这可能是一个错误,因为 sessionCacheLimiter 特别说明了它的用途。

public function behaviors() {
    session_cache_limiter('public');

给予

Cache-Control: public, max-age=10800

并且在不使用 session 时它仍然设置 cookie。这会阻止缓存我们正在使用的 CDN。

Yii 版本 2.0.6.

如果你想使用 \yii\filters\HttpCache 你应该至少设置 lastModified or etagSeed :

[
    'class' => 'yii\filters\HttpCache',
    'lastModified' => function ($action, $params) {
        return time();
    },
    'sessionCacheLimiter' => 'public',
    //'cacheControlHeader' => 'public, max-age=3600', // not needed since it is the default value
],

看这里:https://github.com/yiisoft/yii2/blob/2.0.6/framework/filters/HttpCache.php#L111