On a site, I am dynamically-generating images using PHP's ImageMagick extension. I'm using the .htaccess file to rewrite files ending in .jpg to a php file for dynamic generation:
RewriteRule ^([^_]+).jpg index.php?filename=$1
I am then creating images as JPG inside the PHP file:
$img->setImageFormat('jpeg');
Before echoing the image, I am sending out the following headers:
header("Content-Type: image/jpeg");
header('Expires: Mon, 26 Jul 2027 05:00:00 GMT');
header("Pragma: cache");
header("Cache-Control: max-age=290304001");
However, using Chrome's "Is it Cached?" extension, I can see that the dynamically-generated images are not being cached. Furthermore, Google Chrome's console is saying "Resource interpreted as Document but transferred with MIME type image/jpeg" despite having set the header as Content-Type: image/jpeg
.
So I tried caching with .htaccess, using the following:
<filesMatch "\.(jpg)$">
Header set Cache-Control "max-age=290304001, public"
</filesMatch>
But that also did not work.
So I then tried adding the php
extension to the .htaccess condition:
<filesMatch "\.(jpg|php)$">
Header set Cache-Control "max-age=290304001, public"
</filesMatch>
And that finally worked and the images got cached. So I'm relieved I got it to work, but this trial-and-error approach leaves me uneasy and I don't understand why the PHP cache headers didn't work.
Questions:
1) Is doing the caching via the .htaccess file the correct way to cache images dynamically-generated with PHP?
2) Why are the cache headers being sent out by PHP having no effect?
3) Why is Chrome's console saying "Resource interpreted as Document but transferred with MIME type image/jpeg" when the header has been set to image/jpeg
?
4) Is there a better way of caching dynamically-generated images with PHP (perhaps using pure PHP without .htaccess)?