Search code examples
phpapache.htaccesscachingmod-expires

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


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.


Solution

  • 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)); 
    ?>