我的檔案有問題.htaccess,因為我了解RewriteRule重寫 URL 的幫助。但是當我嘗試以下兩種情況時,它不起作用。
#1 第一個RewriteRule有效,第二個無效
RewriteRule ^([a-zA-Z0-9_-] )$ index.php?idcat=$1 [L] #working
RewriteRule ^([a-zA-Z0-9_-] )$ index.php?idl=$1 [L] #not working
#2 RewriteRule 不適用于破折號,但適用于斜線和下劃線。
RewriteRule ^([a-zA-Z0-9_-] )-([a-zA-Z0-9_-] )$ index.php?idl=$1&iddis=$2 [L] #not working
RewriteRule ^([a-zA-Z0-9_-] )_([a-zA-Z0-9_-] )$ index.php?idl=$1&iddis=$2 [L] #working
RewriteRule ^([a-zA-Z0-9_-] )/([a-zA-Z0-9_-] )$ index.php?idl=$1&iddis=$2 [L] #working
那么如何解決這些問題呢?有人對我有什么建議嗎?
uj5u.com熱心網友回復:
#1 第一個 Rewriterule 有效,但第二個無效
RewriteRule ^([a-zA-Z0-9_-] )$ index.php?idcat=$1 [L] #working RewriteRule ^([a-zA-Z0-9_-] )$ index.php?idl=$1 [L] #not working
因為您在兩個規則中使用相同的模式,所以第一個規則總是“獲勝”,而第二個規則永遠不會被觸發。這本質上處理如下(偽代碼):
if (the URL matches the pattern "^([a-zA-Z0-9_-] )$") {
rewrite the request to "index.php?idcat=<url>"
}
elseif (the URL matches the pattern "^([a-zA-Z0-9_-] )$") {
rewrite the request to "index.php?idl=<url>"
}
如您所見,第二個代碼塊永遠不會被處理,因為運算式是相同的。
換句話說,您將如何確定表單的請求/foo應該重寫為index.php?idcat=foo還是index.php?idl=foo?您不能將請求重寫為兩者。
在這種特殊情況下,您也許可以將所有內容重寫為index.php?id=<url>并讓您的腳本決定它應該是idcat還是idl. 否則,這兩個 URL 需要有所不同(以及您用來匹配 URL的模式),以便您確定應該如何重寫 URL。
#2 Rewriterule 不適用于破折號,但適用于斜線和下劃線。
RewriteRule ^([a-zA-Z0-9_-] )-([a-zA-Z0-9_-] )$ index.php?idl=$1&iddis=$2 [L] #not working RewriteRule ^([a-zA-Z0-9_-] )_([a-zA-Z0-9_-] )$ index.php?idl=$1&iddis=$2 [L] #working
這兩個規則都有相同的問題,具體取決于請求的 URL。這是因為您使用的模式/正則運算式是“模棱兩可的”。用于匹配和值的兩個子模式(分隔符的任一側)中的每一個都包含與預期分隔符或相同的字符。但是,在第三條規則(未顯示)中,您使用 a作為分隔符,它不會出現在周圍的子模式中,因此沒有歧義,idliddis-_/
例如,表單的 URL 應該如何(或者您期望)/foo-bar-baz與第一條規則匹配?由于第一個子模式使用貪婪量詞 ,它將捕獲foo-bar并將baz請求重寫為index.php?idl=foo-bar&iddis=baz.
為避免這種“歧義”,您需要確保子模式之間的分隔符(即 和 的值之間idl)iddis與子模式中使用的字符(或至少兩個子模式之一)不同。
這通常可以通過使正則運算式盡可能具體來解決。IE。僅匹配idl和中的有效字符iddis。
要開始解決此問題,您需要首先確定您嘗試匹配的精確 URL,然后再實施規則以匹配它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482029.html
