2017-02-12 40 views
0

我試圖改變這個URL Apache的mod_rewrite的規則不符合

http://www.example.com/test/products-list.php?category=cars&subcategory=coupe&color=blue

http://www.example.com/test/products/cars/coupe/blue

這是我使用的規則:

RewriteRule products/(.*)/(.*)/(.*)/ /test/products-list.php?category=$1&subcategory=$2&color=$3 
RewriteRule products/(.*)/(.*)/(.*) /test/products-list.php?category=$1&subcategory=$2&color=$3 

適用於以下網址:

http://www.example.com/test/products/cars ----> not working 
http://www.example.com/test/products/cars/ ----> not working 
http://www.example.com/test/products/cars/coupe ----> not working 
http://www.example.com/test/products/cars/coupe/ ----> working 
http://www.example.com/test/products/cars/coupe/blue ----> working 
http://www.example.com/test/products/cars/coupe/blue/ ----> working 

我該如何解決那些不起作用的3種情況?另外,它不工作的原因是什麼?

回答

1

我認爲你的表情是在產品之後尋找3或4'/'。

您的三個捕獲(.*)正在使用「0或更多」重複運算符'*',但是您的三個是必需的。

我相信http://www.example.com/test/products/cars//會測試工作。

現在...如何解決它?

我想你會需要三個不同的重寫每個搜索情況。

  1. 類別
  2. 類別和子類別
  3. 類別,子類別和顏色

您將在下面看到,我已經使用了「+」「重複操作符」給力至少1個字符在拍攝類別,子類別顏色

'/?'在表達式的末尾指示'/'是可選的。這將把你的兩個規則結合成一個。

RewriteRule products/(.+)/? /test/products-list.php?category=$1 
RewriteRule products/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2 
RewriteRule products/(.+)/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2&color=$3 

請讀者注意,我沒有做過的Apache的mod_rewrite了很多年,但我認爲這只是一個正則表達式匹配的問題。

+0

作品像魅力,謝謝! – nick