2009-05-04 117 views
20

我正在尋找重寫多個子字符串的網址。一個子字符串被請求作爲一個子目錄,而另一個被請求作爲正常的查詢字符串參數。mod_rewrite規則匹配問號正則表達式

例如,我想從

http://www.mysite.com/mark/friends?page=2 

重寫URL到

http://www.mysite.com/friends.php?user=mark&page=2 

我能夠用問號字符除外做到這一點。這是我的重寫規則:

... 
RewriteEngine On 
RewriteBase/
RewriteRule ^([A-Za-z0-9-_]+)/friends[?]?([^/\.]+)?$ friends.php?user=$1&$2 [L] 

如果我將問號更改爲任何其他字符,它的效果很好。看來問題在於'?'字符被錯誤地解釋爲新的查詢字符串的開始。

我需要傳遞出現在/ user/friends之後的任何參數。我該如何做到這一點?

回答

33

您應該使用[QSA]標誌而不是試圖重寫查詢字符串。 [QSA]將查詢字符串傳遞給重寫的URL。

所以你的規則應該是這樣的:

... 
RewriteEngine On 
RewriteBase/
RewriteRule ^([A-Za-z0-9-_]+)/friends/? friends.php?user=$1 [QSA,L] 

你的情況很相似,the example given for using the QSA flag in the mod_rewrite cookbook

+0

感謝您的回答。工作得很好&我現在正在閱讀食譜。 – markb 2009-05-05 12:56:55

+0

超級解決方案,它也適用於我,雖然我編輯了我的條件代碼:RewriteRule ^([A-Za-z0-9 -_] +).php? pindex.php?typeofpage = $ 1 [QSA,L] – 2016-07-11 14:23:55

10

The query is not part of the URL path and thus cannot be processed with the RewriteRule directive。這隻能通過RewriteCond指令完成(請參閱%{QUERY_STRING})。

as Chad Birch already said它只需將QSA flag設置爲自動獲取附加到新URL的原始請求查詢即可。

+0

QSA有一個問題列在https://stackoverflow.com/questions/16468098/what-is-l-in-qsa-l-in-htaccess/16468677#comment79837245_16468677 。此外,rewritecond query_string無法區分含有查詢字符串的請求,與使用裸體查詢字符串的請求(即單個問號而沒有其他字符)。有沒有辦法區分這兩個請求? – Pacerier 2017-09-27 06:20:07

1

除了使用重寫標誌QSA,您還可以使用QUERY_STRING環境變量,如下圖所示:

RewriteEngine On 
RewriteBase/
RewriteRule ^([A-Za-z0-9-_]+)/friends$ /friends.php?user=$1&%{QUERY_STRING} 

和有關

http://www.example.com/mark/friends?page=2 

將被改寫的URL(如指定):

http://www.example.com/friends.php?user=mark&page=2