Using mod_rewrite I use this to test if a file exists:

RewriteCond /home/myact/public_html/pagecache%{REQUEST_URI}/index.html -f

How can I test if the file exists and is less than 5 minutes old?

Dani AI

Generated

Short answer: mod_rewrite has file-existence tests (like -f) but no built-in way to test file modification time. Since asked about "script or Apache" and wants it in a RewriteCond, two practical approaches follow.

If you must keep the check inside mod_rewrite (server/vhost config only), use a RewriteMap program that returns 1 when the cache file exists and is younger than 300 seconds. Place the RewriteMap in the server or vhost config (it is not allowed in .htaccess) and call it from a RewriteCond. See the mod_rewrite docs for context: mod_rewrite documentation and the RewriteMap page: RewriteMap (program) docs.

Example sketch (server config + helper program):

RewriteEngine On
RewriteMap fresh prg:/usr/local/bin/freshmap.pl
RewriteCond ${fresh:%{REQUEST_FILENAME}} ^1$
RewriteRule ... [L]
#!/usr/bin/perl
$|=1;
while (<STDIN>) {
  chomp;
  if (-f $_) { print (time - (stat($_))[9] < 300) ? "1\n" : "0\n"; }
  else { print "0\n"; }
}

If you do not have server config access, implement the age check in your application (PHP is fine and what you suggested). PHP example using filemtime:

$cache = '/home/myact/public_html/pagecache' . $_SERVER['REQUEST_URI'] . '/index.html';
if (is_file($cache) && (time() - filemtime($cache) < 300)) {
  readfile($cache);
  exit;
}

Tradeoffs: RewriteMap keeps logic in Apache and avoids hitting PHP for cached responses, but requires vhost/server config access and a robust long-running helper. PHP is easiest on shared hosts and simpler to integrate, but you pay the cost of invoking PHP for the cache decision. Consider atomic writes when updating caches and sending appropriate cache-control headers. For other caching strategies, see Apache’s mod_cache docs: mod_cache.

Recommended Answers

All 4 Replies

Using a script or from within Apache?

Using a script or from within Apache?

I would like to do this as a RewriteCond

I think you will need to use a CondPattern in that RewriteCond but not sure if it will work. The CondPattern takes on a perl syntax. So, if you can test it with a Perl test, you'll have it. Sorry, that I don't have more info on that. I've never heard of this type of need before.

I think you will need to use a CondPattern in that RewriteCond but not sure if it will work. The CondPattern takes on a perl syntax. So, if you can test it with a Perl test, you'll have it. Sorry, that I don't have more info on that. I've never heard of this type of need before.

Thanks, in that case I may as well rewrite everything to PHP and let PHP do the work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.