.htaccess RewriteRule for multiple subdomains



我们正在迁移到另一个域,并希望重定向所有旧流量:

en.site1.com/whatever >>> en.site2.com/whatever
cz.site1.com/whatever >>> cz.site2.com/whatever
fr.site1.com/whatever >>> fr.site2.com/whatever
# ...and so on

我们目前正在使用 .htaccess 进行重定向,因此我们更喜欢使用它的解决方案。RewriteRule 本身看不到域名 (*.example.com),因此我们必须使用 RewriteConds:

RewriteCond %{HTTP_HOST} en.site1.com
RewriteRule ^(.*)$ http://en.site2.com/$1 [R=301]
RewriteCond %{HTTP_HOST} cz.site1.com
RewriteRule ^(.*)$ http://cz.site2.com/$1 [R=301]
RewriteCond %{HTTP_HOST} fr.site1.com
RewriteRule ^(.*)$ http://fr.site2.com/$1 [R=301]
# ...and so on

对 X 支持的语言中的每一种都执行此操作过于冗长。我想象一个解决方案,它将使用正则表达式或其他东西,而不是列出所有语言:

# $0 is the regex match from RewriteCond
RewriteCond %{HTTP_HOST} ^(.*).site1.com
RewriteRule ^(.*)$ http://$0.site2.com/$1 [R=301]

这可能吗?或者 .htaccess 中还有其他方法不包括广泛的复制粘贴吗?

您可以从RewriteCond捕获正则表达式变量,其方式与从 RewriteRule 捕获正则表达式变量的方式大致相同。

当您反向引用捕获的变量时,语法的不同之处在于您使用%而不是$

例如。而不是:

RewriteCond %{HTTP_HOST} en.site1.com
RewriteRule ^(.*)$ http://en.site2.com/$1 [R=301]
RewriteCond %{HTTP_HOST} cz.site1.com
RewriteRule ^(.*)$ http://cz.site2.com/$1 [R=301]
RewriteCond %{HTTP_HOST} fr.site1.com
RewriteRule ^(.*)$ http://fr.site2.com/$1 [R=301]

您可以使用:

RewriteCond %{HTTP_HOST} ([a-z]{2}).site1.com
RewriteRule ^(.*)$ http://%1.site2.com/$1 [R=301]
用于多个

子域重定向特定的特定路径重定向。 请在您的 .htaccess 文件中添加以下代码。

RewriteCond %{HTTP_HOST} abc.com$ [NC]
RewriteRule ^ abcd.com%{REQUEST_URI} [R=301,L,NE]
RewriteCond %{HTTP_HOST} ab.com$ [NC]
RewriteRule ^ abs.com%{REQUEST_URI} [R=301,L,NE]

最新更新