图片过期时间

时间:2010-05-29 07:41:23

标签: php image caching

谷歌页面速度工具建议我为图片等设置“过期”标题。但是为图像设置过期标题的最有效方法是什么?

现在使用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 );

但是当然这会在第一次请求时为我的图像增加额外的加载时间,我想知道是否有更好的解决方案。

2 个答案:

答案 0 :(得分: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="" />

答案 1 :(得分:2)