2012-02-22 115 views
0

我正在PHP中開發一個相當簡單的文件瀏覽器。PHP文件瀏覽器mod_rewrite

該文件位於/家庭/網絡/網絡/歸檔

應該匹配在存檔對應的文件/文件

/files/sub/file.txt => /home/web/www/archive/sub/file.txt (dump as is) 
/files/file.png => /home/web/www/archive/file.png (dump as is) 
/files => /home/web/www/archive (directory, handled by /home/web/www/index.php) 
/files/sub => /home/web/www/archive/sub (directory, handled by /home/web/www/index.php) 

我希望我的.htaccess認識到,如果它是一個請求檔案/下的檔案,如果是這樣,只需輸出檔案。如果沒有發送到index.php。

回答

0

在你的.htaccess下面的內容將發送任何不是一個文件到您的index.php

RewriteCond %{REQUEST_URI} !\/files\/(.*)\.[a-z]+$ 
RewriteRule .* index.php 

所以不具有一個文件名終止的任何請求(.JPG,.BAT,。 txt,.etc)將轉到您的索引。

已更新,所以它現在應該工作。

+0

的請求不指向該文件直接所以這是行不通的。 – user568068 2012-02-22 14:11:46

+0

在你的問題中,你說的請求是'/files/sub/file.txt =>/home/web/www/archive/sub/file.txt'或'/ files/sub =>/home/web/www /存檔/ sub'。所以你的第一個請求直接指向一個文件,所以它會被htaccess忽略,第二個請求指向一個文件夾,所以它會去索引。 – Avanche 2012-02-22 14:15:51

+0

但如果請求是/ files,REQUEST_FILENAME將不匹配/ home/web/www/archive,它會嘗試匹配不存在的/ home/web/www /文件。請求是**從不** /檔案。 – user568068 2012-02-22 14:24:39

1

可以使用-f標誌爲:

RewriteEngine On 

# if the request is for /archive.. 
RewriteCond %{REQUEST_URI} ^\/archive\/ 
# and the request is not for a file 
RewriteCond %{REQUEST_FILENAME} !-f 

# send to index.php 
RewriteRule .* index.php [L] 

請注意,這也重定向到index.php文件請求不存在的文件。您可以爲目錄RewriteCond %{REQUEST_FILENAME} -d添加肯定性檢查,因此只有在請求目錄時纔會重定向。

Documentation in the apache docs with all flags like -f, -d, ...

+0

請求不是/ archive ...它是/ files ...這意味着我不能直接使用!-f。 – user568068 2012-02-22 14:11:11

0
RewriteCond %{REQUEST_URI} ^/files/(.*)$ 
RewriteCond %{DOCUMENT_ROOT}/archive/%1 -f 
RewriteRule .* %{DOCUMENT_ROOT}/archive/%1 [L] 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule^index.php [L]