2013-08-21 36 views
1

我有一個子pics.mysite.com我用來加載圖像,所以當加載圖像的URL被rewrited圖像的src會像http://pics.mysite.com/image.png錯誤500重寫URL後加載圖像

裏面的另一個文件夾(pics_files),其中有這樣的文件:

RewriteEngine On 
RewriteBase/

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ pics_files/$1 [L,QSA] 

工作正常,但現在我有一個問題。 如果圖像不存在,它會創建一個Internal Server Error - 500,但我希望能夠加載一個「錯誤」圖像,如errorImg.png,但到目前爲止我不能。

如果圖像不存在,我該如何將url重寫爲errorImg.png

回答

1

這種替換代碼:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 
RewriteBase/

RewriteCond %{HTTP_HOST} ^pics\.mysite\.com$ [NC] 
RewriteRule ^$ /errorImg.png [L] 

# if valid image file then load it from /pics_files/ directory 
RewriteCond %{DOCUMENT_ROOT}/pics_files/$1 -f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /pics_files/$1 [L] 

# if not-existing image file then load /pics_files/errorImg.png 
RewriteCond %{DOCUMENT_ROOT}/pics_files/$1 !-f 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /errorImg.png [L] 
+0

謝謝你,它工作正常。但我需要改變一件事。而不是加載從pics_folder errorImg.png我需要它在根文件夾(之前的文件夾)。我嘗試了「RewriteRule ^(。*)$ /errorImg.png [L]」,但它沒有奏效!非常感謝你。 – Pedro

+0

好的,現在檢查已編輯的代碼。 – anubhava

+0

太棒了!很棒。非常感謝你。 – Pedro

1

這是因爲您正在捕獲整個URI並將其路由到pics_files目錄。如果圖像不存在,!-f條件通行證和URI被再次改寫,所以你最終:

/pics_files/pics_files/image.png 

不存在,所以URI再次改寫:

/pics_files/pics_files/pics_files/image.png 

不存在,所以URI被再次改寫,等,等

而不是檢查如果URI是不是一個文件或目錄作爲條件,檢查目標圖像actualy存在:

RewriteEngine On 

RewriteBase/

RewriteCond %{DOCUMENT_ROOT}/pics_files%{REQUEST_URI} -f 
RewriteRule^/pics_files%{REQUEST_URI} [L] 
+0

謝謝您的回答是非常有用的。但你沒有說關於加載「錯誤」圖片:) – Pedro