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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With