I need .htaccess to cache php pages, and expire them at the beginning of every hour (xx:00:00)

989 views Asked by At

I want to cache a number of php pages that display different data at the beginning of every hour (xx:00:01)?

So far, I've found a way of cacheing a page +1hour from the time of accessing (or modifying the file), but if the user accesses the page at xx:59:00, then at xx+1:00:01, he will see the cache'd page data, not the newly displayed data.

What do I need to write to get a regular, "top-of-the-hour" cache expiry, preferably using .htaccess?

Final code (non htaccess):

$nexthour = mktime(date("H")+1, 00, 20) - mktime();
header("Cache-Control: public, must-revalidate, max-age=".$nexthour.", s-maxage=".$nexthour);

At the top of each page.

2

There are 2 answers

4
Gerben On BEST ANSWER

can be done with htaccess but is kind of a pain.

RewriteCond %{TIME_WDAY} ^0$
RewriteCond yourfile.php - [E=daystring:SUN]
#etc (7x)

RewriteCond %{TIME_MON} ^0$
RewriteCond yourfile.php - [E=monthstring:JAN]
#etc (12x)

Header set "Expires" "%{daystring}, %{TIME_DAY} %{monthstring} %{TIME_YEAR} %{TIME_HOUR}:59:59 GMT "

Better to just do this in the PHP itself (after session_start()).

<?php
$nexthour = mktime (date("H"), 59, 59);
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', $nexthour)); 
?>
2
Brigand On

One option is to set up a cron job to run on the hour. You could have it update static html files for all it cares, and then have Apache serve those.

(This wouldn't be a .htaccess based solution.)