Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redirect to the newest file in directory using .htaccess?

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

  • I have a link to file: http://something.com/images/some/image_001.png
  • If this file doesn't exists I want to redirect to the newest file in /images/some directory

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.

like image 703
Adrian Serafin Avatar asked Nov 13 '22 17:11

Adrian Serafin


1 Answers

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

like image 53
arober11 Avatar answered Nov 15 '22 08:11

arober11