图片过期时间 [英] Image expire time

查看:158
本文介绍了图片过期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The google page speed tool recommends me to set 'Expires' headers for images etc. But what is the most efficient way to set an Expires header for an image?

现在使用htaccess将所有图像请求重定向到imagehandler.php:

In now redirect all image requests to an imagehandler.php using htaccess:

/*
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 );

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

But of course this adds extra loading time for my images on first request, and I was wondering if there was a better solution for this.

推荐答案

您可以在 .htaccess 文件。

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

在AskApache上找到

当然,如果你想改变图像,它们将不会下载再次,直到他们到期

Of course, if you want the images changed, they won't be downloded again until they expire.

你可以通过做这样的事情来解决这个问题

You can solve that by doing something like this

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

}

我只使用 substr( )使它缩短一点。他们碰撞的可能性最小,但可能发生。一定要测试一下。

I just use the substr() to make it a little shorter. The chances of them colliding is minimum, but may happen. Be sure to test it.

像这样使用

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

这篇关于图片过期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆