php header()函數設定頁面Cache緩衝

來源:互聯網
上載者:User

手冊上,我們對於cache都是寫著如何設定,以便讓代碼不被cache:

 代碼如下 複製代碼

header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // Date in the past


而且在設定的時候還得注意在header前不能有輸出,否則header設定無效,但都沒有寫過,如何給版面設定Cache,雖然我們知道有一些辦法,比如 E-TAG之類的。當然也有簡單的設定:

比如我們在輸出前,對內容進行md5,將它當成e-tag只要沒變化,就不會有影響。也有其他的方式:

 代碼如下 複製代碼

$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts"); header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");


緩衝1小時,主要是到期時間得用gmdate來設定,而不是date,這個要注意,其他都差不多。maxage要和expire能夠對得上。

對於PHP產生的動態內容,只需要在內容輸出之前輸出強制緩衝的header即可,比如下面的代碼即要求瀏覽器快取檔案1個月:

 代碼如下 複製代碼

<?php
  header("Cache-Control: public");
  header("Pragma: cache");

  $offset = 30*60*60*24; // cache 1 month
  $ExpStr = "Expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
  header($ExpStr);
?>

對於靜態檔案,一般的伺服器都支援第3級緩衝狀態。要想達到第四級的緩衝效果,要麼像之前GZIP壓縮那樣,用PHP外包一層,然後用PHP處理。要麼需要伺服器端的支援,APACHE的一個模組mod_expires支援給檔案添加expires header。把下面的代碼加入你的blog目錄下的.htaccess檔案,如果你的伺服器安裝了mod_expires模組,則將自動生效,圖片等強制緩衝一個月,html文檔緩衝10分鐘。如果該模組沒有安裝,也不會出錯。

 代碼如下 複製代碼

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000
ExpiresByType application/x-shockwave-flash A2592000
ExpiresByType text/css A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType text/html A600
</IfModule>


在這裡有mod_expires更詳細的文檔和教程。不過我要說明的是,mod_expires在絕大多數伺服器上都沒安裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.