2011-10-20 58 views
0

我有我使用的圖像和其他類型的文件的模板系統,所以這裏是幾個模板樣本,他們的形象mod_rewrite的,尋找不存在的文件在不同的文件夾

/templates/template1/images/image1.jpg 
/templates/template1/images/header/red/new/image1.jpg 
/templates/template1/image2.jpg 
/templates/template2/images/image2.jpg 
/templates/template2/image2.jpg 

現在,有時候模板會丟失圖片或文件,在這種情況下,我希望將用戶重定向到「默認」模板,同時保留url的其餘部分。

所以對於例子給出的,如果圖像中沒有找到用戶應該被重定向到

/templates/default/images/image1.jpg 
/templates/default/images/header/red/new/image1.jpg 
/templates/default/image2.jpg 
/templates/default/images/image2.jpg 
/templates/default/image2.jpg 

這是我在做這項工作的嘗試,它在虛擬主機文件的定義

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_URI} !^/templates/default/(.*)$ 
RewriteRule ^/templates/(.*)/(.*) /templates/default/$2 [R] 

現在這個

重定向/templates/template1/images/image1.jpg到/templates/default/image1.jpg,然後拋出500錯誤。

我在這裏做錯了什麼?

+0

有關500錯誤的Apache錯誤日誌中的任何詳細信息? – megaflop

+0

嘗試在'^/templates /(.*)/(.*)'中添加'$'使'^/templates /(.*)/(.*)$' – megaflop

回答

1

我不知道你爲什麼要獲得500,但ReqriteRule會因爲第一個.*的貪婪而在多個子目錄中出現問題。

請考慮/templates/template1/images/header/red/new/image1.jpg的請求。如果這個文件不存在然後在^/templates/(.*)/(.*),第一個(.*)將匹配所有的「template1/images/header/red/new」,第二個(。*)將匹配「image1.jpg」,所以你會得到重定向到「/templates/default/image1.jpg」。

一個更好的規則:

RewriteRule ^/templates/[^/]+/(.*)$ /templates/default/$1 [R] 

或者,如果你知道模板目錄只能有字母數字字符,下劃線或連字符,這是更好的是:

RewriteRule ^/templates/[a-zA-Z0-9_-]+/(.*)$ /templates/default/$1 [R] 

嘗試儘可能保持正則表達式。

相關問題