2015-11-20 42 views
-1

如何使用RewriteRule重定向?
來自:使用RewriteRule重定向

www.example.com/ca/blog/something 

要:

www.example.com/ca/test.php?url=something 

當然 「東西」 可能會改變。網址的其他部分將始終保持不變。
最後,我想用test.php與參數設置:

$url = $_GET['url']; 
echo $url; 

我已經在.htaccess刪除所有其他規則,以確保沒有衝突。請解釋解決方案。我對正則表達式很陌生。

+0

問題出在哪裏,爲什麼是負面的? – Nrc

回答

0
RewriteEngine On 
RewriteRule ca/blog/(.*)$ /ca/test.php?url=$1 [L,R=301] 

/blog/後捕獲的一切,並賦予它作爲一個參數test.php。句號(。)表示「每個字符」,星號(*)的意思是「儘可能多地找到(或沒有)」,括號將捕獲結果。如果你想確保在test.php URL參數不爲空,您可能需要使用一個加號(+),像這樣:

RewriteRule ca/blog/(.+)$ /ca/test.php?url=$1 [L,R=301] 

這意味着「儘可能多的字符,但必須有至少一個」。另外,這裏有is a nice online tester

+0

如果我在bowser中編寫解決方案:請求的URL/ca /​​ blog /在這臺服務器上找不到東西。如果寫www.example.com/ca/test.php?url=something我得到:「東西」 – Nrc

+0

你把你的'.htaccess'文件放在哪裏?它必須位於根文件夾中。 – Jan

+0

是的,它位於根文件夾中。昨天我有其他規則可行。我不知道爲什麼,我只是有這個問題 – Nrc

0

嘗試:

RewriteEngine On 

RewriteBase/
# at the entrance of RewriteRule: ca/blog/something 
RewriteRule ^ca/blog/(.*)$ ca/test.php?url=$1 [QSA] 
# after transformation: "ca/blog/something" -> "ca/test.php?url=something" 
+0

它給了我一樣的錯誤比Jan – Nrc

+0

爲什麼「RewriteBase /」我想我也必須在之前放置「RewriteEngine On」? – Nrc

+0

@Nrc是的,你應該在文件的開頭寫上'RewriteEngine On'。我認爲在你的情況下'RewriteBase'不是必需的。 – Suvitruf