Kevin Craft
Kevin Craft

Reputation: 879

Add Apache header if not set by application

I'm trying to control the caching of files within a certain directory. I want the default cache time to be 15 minutes, but I want to let the application change it if necessary. For example, I may have a PHP script that I want to refresh every 1 minute, so I'll set the cache-control headers within PHP for that script. But for all of the other files I just want the cache time to be 15 minutes, and some of those are static files, so I can't just set a default cache-time in PHP.

I currently have this in my Apache config:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Header set Cache-Control "max-age=900"
</Directory>

This works great for 99% of the cases, where I just want a 15 minute cache. However, if my PHP script sets a cache-control header, then this setting will overwrite it.

I've looked at the documentation for mod_header and none of the settings (unset, add, append, etc.) seem to give me what I need.

Thanks in advance.

Upvotes: 1

Views: 880

Answers (2)

speeves
speeves

Reputation: 1376

Take a look at mod_expires instead http://httpd.apache.org/docs/2.2/mod/mod_expires.html. The docs say that it won't overwrite headers created by your PHP script:

"When the Expires header is already part of the response generated by the server, for example when generated by a CGI script or proxied from an origin server, this module does not change or add an Expires or Cache-Control header."

Here is an example config for mod_expires:

 <IfModule mod_expires.c>
     ExpiresActive on
     ExpiresDefault A600
     ExpiresByType image/gif "access plus 1 day"
     ExpiresByType image/jpeg "access plus 1 day"
     ExpiresByType image/png "access plus 1 day"
     ExpiresByType image/x-icon "access plus 1 day"
     <FilesMatch "\.(php|php4)$">
         ExpiresByType text/html "now"
     </FilesMatch> 
 </IfModule>

Taken from http://howto.gumph.org/content/reduce-webserver-bandwidth/

Good luck!

Upvotes: 1

keepwalking
keepwalking

Reputation: 2654

According to php manual

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Upvotes: 0

Related Questions