2017-10-12 73 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 –