2017-10-12 77 views
1

我想從舊網站URL重定向到新網站URL。 我在htaccess文件中有很多規則。 請看下面的例子:通用重寫規則將查詢附加到htaccess中的所有定義的重寫規則

RewriteRule ^blog/one$ http://www.newsite.com/blog/x/ [R=301,L] 
RewriteRule ^blog/two$ http://www.newsite.com/blog/y/ [R=301,L] 
RewriteRule ^blog/three$ http://www.newsite.com/blog/z/ [R=301,L] 
and so on.......... 

重定向工作正常。 現在我想追加一個查詢字符串「?key = value & anotherKey = anotherValue」到所有目標網址。 有沒有辦法通過單行代碼來完成這項任務? 或者我需要將這個查詢追加到所有的url。

這裏是我想要一個例子:

RewriteRule ^blog/one$ http:www.newsite.com/blog/x/?key=value&anotherKey=anotherValue [R=301,L] 

編輯: 完整的htaccess:

<IfModule mod_rewrite.c> 

RewriteEngine On 
RewriteBase/

#Custom redirection Starts form here 

RewriteCond %{QUERY_STRING} ^$ 
RewriteRule ^.*$ $0?key=value&anotherKey=anotherValue [L,NC] 

#home page redirection 
RewriteRule ^$ http://newsite.com/ [R=301,L] 

#Blog Rewrite Rules 
RewriteRule  ^blog/this-blog-is-included-for-redirection/?$ http://newsite.com/blog/ [R=301,L] 

#Custom redirection ends here 


RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule . /index.php [L] 
</IfModule> 

當我訪問此網址: oldsite.com/blog/this-blog-is -included-for-redirection/

它重定向到: newsite.com/blog/?key=value & anotherK ey = anotherValue

這很好。

當我訪問此網址: oldsite.com/blog/this-blog-is-exluded-for-redirection/

它重定向到: oldsite.com/blog/this-blog-is- exvded-for-redirection /?key = value & anotherKey = anotherValue

這裏我不想附加查詢。

+0

規則工作。我想通過一行或幾行代碼將查詢字符串附加到所有目標網址。有沒有辦法做到這一點? –

+0

你可以這樣做:http://www.newsite.com/blog/x/?param1 = x&param2 = y''[R = 301,L,QSA]' –

+0

不是'^ blog/one'你可以用'/ block /(.*)'將所有博客重寫爲'.../blog/$ 1?key = ...'。問題是你有一個重定向,而不是重寫,所以這可能會導致無限循環,所以你可能需要改進正則表達式或添加條件 – apokryfos

回答

1

你可以保持一個通用的規則之前,您的重定向規則設置查詢字符串和重定向規則將自動結轉查詢字符串目標的URI:

RewriteEngine On 

# generic rule for query string 
RewriteCond %{QUERY_STRING} ^$ 
RewriteRule ^blog/(?:one|two|three)/?$ $0?key=value&anotherKey=anotherValue [L,NC] 

RewriteRule ^blog/one/?$ http://www.newsite.com/blog/x/ [R=301,L,NC] 
RewriteRule ^blog/two/?$ http://www.newsite.com/blog/y/ [R=301,L,nC] 
RewriteRule ^blog/three/?$ http://www.newsite.com/blog/z/ [R=301,L,NC] 
+0

我剛剛添加了R = 301在你的規則中,即RewriteRule^blog /(?: one | two | three)/?$ $ 0?key = value&anotherKey = anotherValue [R = 301,L,NC]現在它工作正常。在此之前,網址「oldsite.com/blog」不起作用,URL「oldsite.com/blog/」和「oldsite.com/blog/anything」只能正常工作。你能解釋一下你的答案嗎?我們可以在htaccess文件的任何地方使用通用規則嗎? –

+0

當然。我只添加了一條通用規則。該規則檢查是否沒有查詢字符串,並且當條件成功時,它會在模式'^ blog /(?: one | two | three)/?$'定義的某些選定URI中添加所需的查詢字符串。由於這個原因,下一組規則將獲得已經附加的通用查詢字符串。 – anubhava

+0

當它重定向到newsite.com時,它附加了很好的查詢字符串, 但我從重定向中排除了一些URL,並且還將查詢附加到該URL。 我怎樣才能避免追加查詢oldsite.com –