2010-05-29 18 views
1

谷歌頁面速度工具建議我爲圖片等設置「過期」標題。但是,爲圖片設置過期標題的最有效方法是什麼?圖片過期時間

在現在使用的htaccess的重定向所有的圖像請求發送到imagehandler.php:

/* 
HTTP/1.1 404 Not Found, HTTP/1.1 400 Bad Request and content type detection stuff 
... 
*/ 

header("Content-Type: " . $content_type); 
header("Cache-Control: public"); 
header("Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($path))." GMT"); 
header("Expires: ". date("r",time() + (60*60*24*30))); 
readfile($path); 

不過,當然這會增加額外的加載時間我的第一個請求的圖像,我想知道是否有一個更好的解決方案爲了這。

回答

3

您可以將其添加到.htaccess文件中。

<FilesMatch "\.(ico|jpg|jpeg|png|gif)$"> 
Header set Cache-Control "max-age=290304000, public" 
</FilesMatch> 

Found on AskApache

當然,如果你想改變圖像,他們將不會再被降級,直到他們到期

你可以做這樣的

function getImage($path) { 
    // may need to add a DOCROOT constant here before filemtime() argument 
    return $path . '?m=' . substr(filemtime($path) -5); 

} 

東西,我只是用substr()讓它短一點解決。他們碰撞的機會是最小的,但可能發生。一定要測試它。

使用方法如下

<img src="<?php echo getImage('path/to/your/image.jpg'); ?>" alt="" /> 
+0

謝謝。這樣做的訣竅:) – Jens 2010-05-29 20:22:08

+0

這將是很好,如果你解釋的神奇數字290304000的意思,而不是簡單地使用它 – Alexxus 2015-06-05 08:01:25

+0

@Alexxus我認爲這是幾秒鐘。 – alex 2015-06-09 00:58:23