How to Cache Images Dynamically-Generated with PHP?
<p>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:</p>

<pre><code>RewriteRule ^([^_]+).jpg index.php?filename=$1
</code></pre>

<p>I am then creating images as JPG inside the PHP file:</p>

<pre><code>$img-&gt;setImageFormat('jpeg');
</code></pre>

<p>Before echoing the image, I am sending out the following headers:</p>

<pre><code>header("Content-Type: image/jpeg");
header('Expires: Mon, 26 Jul 2027 05:00:00 GMT');
header("Pragma: cache");
header("Cache-Control: max-age=290304001");
</code></pre>

<p>However, using Chrome's "<em>Is it Cached?</em>" extension, I can see that the dynamically-generated images are <strong>not</strong> being cached.  Furthermore, Google Chrome's console is saying "<em>Resource interpreted as Document but transferred with MIME type image/jpeg</em>" despite having set the header as <code>Content-Type: image/jpeg</code>.</p>

<p>So I tried caching with .htaccess, using the following:</p>

<pre><code>&lt;filesMatch "\.(jpg)$"&gt;
Header set Cache-Control "max-age=290304001, public"
&lt;/filesMatch&gt;
</code></pre>

<p>But that also did <strong>not</strong> work.</p>

<p>So I then tried adding the <code>php</code> extension to the .htaccess condition:</p>

<pre><code>&lt;filesMatch "\.(jpg|php)$"&gt;
Header set Cache-Control "max-age=290304001, public"
&lt;/filesMatch&gt;
</code></pre>

<p>And that <strong>finally</strong> 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.</p>

<p>Questions:</p>

<p>1) Is doing the caching via the .htaccess file the correct way to cache images dynamically-generated with PHP?</p>

<p>2) Why are the cache headers being sent out by PHP having <strong>no effect</strong>?</p>

<p>3) Why is Chrome's console saying "<em>Resource interpreted as Document but transferred with MIME type image/jpeg</em>" when the header has been set to <code>image/jpeg</code>?</p>

<p>4) Is there a better way of caching dynamically-generated images with PHP (perhaps using pure PHP without .htaccess)?</p>