簡體   English   中英

如何在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沒有輸出所有標題的原因,但我仍然不知道如何打開緩存。 事實上,現在它正在積極地通過Cache-Control: no-cache關閉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

並且在沒有使用會話時仍然設置cookie。 這可以防止我們正在使用的CDN的緩存。

Yii版本2.0.6。

如果你想使用\\yii\\filters\\HttpCache你應該至少設置lastModifiedetagSeed

[
    '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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM