Image expire time
The google page speed tool recommends me to set 'Expires' headers fo开发者_运维技巧r images etc. But what is the most efficient way to set an Expires header for an image?
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.
You can add it in the .htaccess
file.
<FilesMatch "\.(ico|jpg|jpeg|png|gif)$">
Header set Cache-Control "max-age=290304000, public"
</FilesMatch>
Found on 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);
}
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.
Use it like this
<img src="<?php echo getImage('path/to/your/image.jpg'); ?>" alt="" />
http://httpd.apache.org/docs/2.0/mod/mod_expires.html
精彩评论