HTTP頭中有個(gè)expires參數(shù),設(shè)置一個(gè)未來的時(shí)間,在這時(shí)間以前,瀏覽器會(huì)先從cache讀取,如果沒有再從服務(wù)器中讀取。對(duì)于像圖片,css,script等靜態(tài)內(nèi)容,只需發(fā)一次http request就可,以后就可從cache中讀取,一方面提高了響應(yīng)時(shí)間,也減少了http rquest的次數(shù)。
具體的格式如下: Expires = "Expires" ":" HTTP-date。
Example: Expires: Thu, 01 Dec 2010 16:00:00 GMT.
Expires有個(gè)缺點(diǎn)就是它只能設(shè)置絕對(duì)時(shí)間,這樣每當(dāng)?shù)竭_(dá)預(yù)設(shè)時(shí)間點(diǎn)后必須重設(shè)expires值。HTTP/1.1提供了一個(gè)新的參數(shù)cache-control可以設(shè)置相對(duì)時(shí)間。
Cache-Control:Max-age
Cache-Control使用max-age直接指定component能被緩存多長(zhǎng)時(shí)間. 它定義了新的方式用秒為單位. 假如當(dāng)前時(shí)間與上次返回時(shí)間差小于上次返回的max-age,那么瀏覽器使用緩存的版本。如果需要緩存10年,你可以這樣指定:
Cache-Control: max-age=315360000
PS: 如果同時(shí)設(shè)置了cache-control和expires,cache-control會(huì)覆蓋expires。
Apache中配置expires
Apache提供了mod_expires.so模塊,可以輕松的設(shè)置expires值,以下是配置的范例:
LoadModule expires_module modules/mod_expires.so
ExpiresActive On
ExpiresDefault "access plus 300 seconds" #默認(rèn)300秒過期
<Directory "/myProject/webResources"> #文件所在目錄
Options FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
ExpiresByType text/html "access plus 1 day" #設(shè)置cache時(shí)間為1天
ExpiresByType text/css "access plus 1 day"
ExpiresByType text/javascript "access plus 1 day"
ExpiresByType image/gif "access plus 1 day"
ExpiresByType image/jpg "access plus 1 day"
ExpiresByType image/png "access plus 1 day"
ExpiresByType application/x-shockwave-flash "access plus 1 day"
參考文檔:
1. http://kuppalli.wordpress.com/2009/07/14/apache-configuration-for-etags-gzip-and-expires-header/
2. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32
3. http://www.meichua.com/archives/168.html
posted on 2010-10-21 09:36
Aaron.Chu 閱讀(2467)
評(píng)論(0) 編輯 收藏