2014-03-04 61 views
0

背景如何用RewriteCond和RewriteRule刪除部分查詢字符串?

我想在URL中替換幾個(3)查詢字符串參數。我們正在轉向一個新的搜索引擎,並且還有很多我們想要繼續工作的鏈接。例子:

http://example.com/search?q=s&restrictBy[foo]=fltr1&restrictBy[baz]=fltr2 -> 
http://example.com/search?q=s&newfoo=fltr1&bazinga=fltr2 

http://example.com/search?q=s&restrictBy[bar]=fltr3 -> 
http://example.com/search?q=s&barista=fltr3 

http://example.com/search?q=s&restrictBy[bar]=fltr1&restrictBy[baz]=fltr2&restrictBy[foo]=fltr3 -> 
http://example.com/search?q=s&barista=fltr1&bazinga=fltr2&newfoo=fltr3 

問題

的第一個參數重寫規則does not look at the query string,所以在保持URL的其餘部分完好的,我不能沒有一個參數。此外,事實上可能存在NONE,SOME或ALL的所有參數,並且IN ANY ORDER正在將我投入循環。

# Does not work :/ 
RewriteRule (.*)restrictBy\[foo\]=(.*) $1newfoo=$2 

# Kinda works, but loses rest of params 
RewriteCond %{QUERY_STRING} restrictBy\[foo\]=([^&]*) 
RewriteRule (.*) $1?newfoo=%1 [L] 

# Kinda works, but doesn't remove old params 
RewriteCond %{QUERY_STRING} restrictBy\[foo\]=([^&]*) 
RewriteRule (.*) $1?newfoo=%1 [QSA,L] 

問題

我怎麼能更換,而不會丟失數據,並沒有額外的數據任何或所有3名PARAMS?從規則

回答

0

刪除QSA覆蓋現有的查詢字符串:

RewriteCond ::%{QUERY_STRING} ::(?:|.*&)restrictBy\[foo\]=([^&]*) 
RewriteCond %1::%{QUERY_STRING} (.*?)::(?:|.*&)restrictBy\[baz\]=([^&]*) 
RewriteCond %1&%2::%{QUERY_STRING} ([^&]*)&(.*?)::(?:|.*&)q=([^&]*) 
RewriteRule ^(.*)$ $1?q=%3&newfoo=%1&bazinga=%2 [L,R] 
+0

感謝您的快速回復。我沒有提到參數可能並不都是存在的,它們可能以不同的順序存在。這仍然是你解決問題的方式嗎? – nachito

+0

那麼'q = s'將永遠在那裏?你有很多參數,這些都是可選的? – anubhava

+0

正確。 'q =東西'將永遠在那裏,其餘的可選 – nachito