我Walf在搬運路線通過路由器類同意是一個更好的主意(尤其是從長遠來看!)比使用.htaccess
重定向。
但是,由於您的問題似乎更多的是爲什麼這不工作,而不是你應該怎麼做,這裏是一個解釋發生了什麼。
我將使用這些URL作爲例子:
localhost:8080
localhost:8080/app
localhost:8080/app/customers/id/5
你的第一條規則:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(www.)?localhost:8080$
RewriteRule ^(.*)$ /views/$1
如你意,這個重寫規則將匹配這不是一個文件,而不是目錄中的任何URL ,並製作到localhost:8080。
localhost:8080 # not matched because it leads to a directory.
localhost:8080/app -> localhost:8080/views/app
localhost:8080/app/customers/id/5 -> localhost:8080/views/app/customers/id/5
你的下一個規則:
RewriteRule ^(/)?$ /views/index.php [L]
重要的是要認識到的RewriteCond陳述僅適用於第一重寫規則跟了上去,因此正被這裏檢查了所有的路徑是非常重要的。
備註:^(/)?$
,因爲您未使用$1
,可簡化爲^/?$
。
localhost:8080 -> localhost:8080/views/index.php
localhost:8080/views/app # not matched
localhost:8080/views/app/customers/id/5 # not matched
符合規定L
標誌,Apache將立即停止當前迭代,並開始從頂部再次匹配。 The documentation is badly worded。因此,localhost:8080/views/index.php
將通過第一條規則運行,不匹配,通過此規則運行,無法匹配,然後由於沒有其他規則存在檢查(但)不會進行重寫。
現在讓我們來看看添加破損規則時會發生什麼。
RewriteRule /id/(.*) customers.php?id=$1
這裏有幾個問題。首先,由於您不需要網址以/id/
開頭,即使您已經重寫了網址,該規則也會始終與包含/id/
的網址匹配。如果您使用^/id/(.*)
對此進行了修改,那麼您仍然會遇到問題,因爲重寫RegEx所測試的字符串已刪除了前導斜槓。最後也是最重要的是,customers.php
不存在於您的根目錄中。
localhost:8080/views/index.php # not matched
localhost:8080/views/app # not matched
localhost:8080/views/app/customers/id/5 -> localhost:8080/customers.php?id=5
這是當前文件中的最後一條規則,所以現在Apache將重新開始。 customers.php
不存在於您的目錄中,因此它將被重寫爲views/customers.php
。沒有其他規則匹配,但URL已更改,所以Apache將重新開始,因爲/views/customers.php
不存在,它將被重寫爲/views/views/customers.php
......此模式將重複,直到達到最大迭代限制並且Apache響應500錯誤。
您可以通過以下幾種方法解決。這將是我的首選方法,但只有當你不能使用路由器。
RewriteEngine on
# Rewrite the main page, even though it is a directory
RewriteRule ^/?$ views/index.php [END]
# Don't rewrite any existing files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .? - [S=999,END]
RewriteRule ^app/?$ views/app/index.php [END]
RewriteRule ^app/id/(.*)$ views/app/customers.php?id=$1 [END]
TL; DR使用基於PHP的路由器。 .htaccess
規則可能令人難以置信地混淆。
/id/(.*)將始終與customers/php?** id **匹配,因此您的規則將始終循環 – Gerrit0
,那麼如何更改該行可以在我的情況下工作? –
對不起,我對這個假設過於倉促,問題不在於這個問題,問題在於你的第一條規則,它總是匹配的,所以總是在你的URL的開頭添加/查看/。 htaccess規則非常容易搞亂。在嘗試很好地回答這個問題之前,我需要學習更多。 – Gerrit0