2012-11-12 45 views
5

我想創建情況的.htaccess規則如下圖所示:我可以使用.htaccess重定向到目錄中最新的文件嗎?

是這樣的可能使用.htaccess?我知道我可以使用RewriteCond檢查文件是否存在,但不知道是否可以重定向到最新的文件。

+1

你不能讓一個腳本(比如PHP)重定向到最新的文件並使用RewriteCond去那裏? – mgarciaisaia

+0

我想我可以,但我正在尋找可能的最快解決方案,並且創建php腳本意味着引入第二個rediraction。我正在考慮使用符號鏈接解決每個目錄中最新文件的解決方案 –

回答

1

改寫到一個CGI腳本是您從的.htaccess唯一的選擇,在技術上你可以使用一個程序化RewriteMap指令在一個的httpd.conf文件重寫規則。

該腳本可以直接提供文件,因此通過內部重寫,邏輯可以完全服務器端,例如,

的.htaccess規則

RewriteEngine On 
RewriteBase/

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

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); 
?> 

注:代碼部分從答案中借用:PHP: Get the Latest File Addition in a Directory

相關問題