Adr*_*fin 5 apache .htaccess redirect
我想为下面的情况创建.htaccess规则:
使用.htaccess可以这样吗?我知道我可以检查RewriteCond是否存在文件,但不知道是否可以重定向到最新文件.
重写为 CGI 脚本是 .htaccess 中的唯一选择,从技术上讲,您可以在httpd.conf文件中使用带有 RewriteRule的编程RewriteMap。
该脚本可以直接为文件提供服务,因此通过内部重写,逻辑可以完全在服务器端,例如
.htaccess 规则
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^images/(.*)$ /getLatest.php [L]
Run Code Online (Sandbox Code Playgroud)
其中getLatest.php类似于:
<?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);
?>
Run Code Online (Sandbox Code Playgroud)
注意:代码部分借自以下答案:PHP:获取目录中的最新文件添加