2013-07-10 51 views
0

我使用URL重寫以下方案:404重定向重寫URL路徑在瀏覽器中完整的URL路徑的作品,但變化

example.com/about/ 
example.com/this/is/a/page/ 

去:

example.com/pages/about/about.php 
example.com/pages/this/is/a/page/page.php 

它工作正常,但在404錯誤,當輸入example.com/badpage/時,它顯示404頁面,但將URL字符串更改爲example.com/pages/badpage/badpage.php

即使404錯誤,如何保持URL不變?

(htaccess的還增加了對 '/' 所請求的URL的末尾,你可以從下面的代碼中看到)


htaccesss代碼:

DirectoryIndex /pages/index/index.php 
ErrorDocument 404 /pages/error/404.php 

RewriteEngine On 

#Removes the www from domain for SEO 
RewriteCond %{HTTP_HOST} ^www\.portal\.example\.com$ [NC] 
RewriteRule ^(.*)$ http://portal.example.com/$1 [L,R=301] 

# Don't fix direct file links 
RewriteCond %{REQUEST_FILENAME} !-f 

RewriteCond %{REQUEST_URI} !(.*)/$ 
RewriteRule ^(.*)$ http://portal.example.com/$1/ [L,R=301] 

RewriteRule  ^([A-Za-z0-9_-]+)/?$ pages/$1/$1.php [NC,L] 
RewriteRule  ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ pages/$1/$2/$2.php [NC,L] 
RewriteRule  ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ pages/$1/$2/$3/$3.php [NC,L] 
RewriteRule  ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ pages/$1/$2/$3/$4/$4.php [NC,L] 

回答

0

您需要在每次重寫之前添加條件以確保您不會盲目地重寫爲不存在的文件。主要地,在端部的4個規則需要有一定的條件:

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/?$ 
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%1.php -f 
RewriteRule^pages/%1/%1.php [NC,L] 

第一條件創建其使用%1反向引用的分組。第二種情況會創建一條您嘗試重寫的路徑,並使用-f檢查該文件是否存在。對於其他人也是如此:

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ 
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%2.php -f 
RewriteRule^pages/%1/%2/%2.php [NC,L] 

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ 
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%3/%3.php -f 
RewriteRule^pages/%1/%2/%3/%3.php [NC,L] 

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$ 
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%3/%4/%4.php -f 
RewriteRule^pages/%1/%2/%3/%4/%4.php [NC,L]