5

I want to create .htaccess rule for situation like below:

Is something like this possible using .htaccess? I know that I can check if file exists with RewriteCond, but don't know if it is possible to redirect to the newest file.

Adrian Serafin
  • 7,665
  • 5
  • 46
  • 67
  • 1
    Can't you make a script (say, PHP) that redirects to the newest file and use RewriteCond to go there? – mgarciaisaia Nov 12 '12 at 16:30
  • I suppose I can, but I'm looking for the fastest solution possible and createing php scripts means introducing second rediraction. I am thinking about solution with symlinks to the newest file in each directory – Adrian Serafin Nov 12 '12 at 17:05

1 Answers1

1

Rewriting to a CGI script is your only option from a .htaccess, technically you could use a programatic RewriteMap with a RewriteRule in a httpd.conf file.

The script can serve the file directly, so with an internal rewrite the logic can be entirely server side e.g.

.htaccess Rule

RewriteEngine On 
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^images/(.*)$  /getLatest.php [L]

Where getLatest.php is something like:

<?php

$dir = "/srv/www/images";
$pattern = '/\.(jpg|jpeg|png|gif)$/';
$newstamp = 0;
$newname = "";

if ($handle = opendir($dir)) {
   while (false !== ($fname = readdir($handle)))  {
     // Eliminate current directory, parent directory            
     if (preg_match('/^\.{1,2}$/',$fname)) continue;
     // Eliminate all but the permitted file types            
     if (! preg_match($pattern,$fname)) continue;
     $timedat = filemtime("$dir/$fname");
     if ($timedat > $newstamp) {
        $newstamp = $timedat;
        $newname = $fname;
      }
     }
    }
closedir ($handle);

$filepath="$dir/$newname";
$etag = md5_file($filepath); 

header("Content-type: image/jpeg");
header('Content-Length: ' . filesize($filepath));
header("Accept-Ranges: bytes");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $newstamp)." GMT"); 
header("Etag: $etag"); 
readfile($filepath);
?>

Note: Code partially borrowed from the answers in: PHP: Get the Latest File Addition in a Directory

Community
  • 1
  • 1
arober11
  • 1,969
  • 18
  • 31