如何重定向到具有多个域的.htaccess文件中的子域

时间:2019-01-01 17:14:00

标签: .htaccess redirect

我有一个.htaccess文件,该文件将example1.com,example2.com和example3.com发送到服务器上的其他文件

我想这样做,以便example3.com临时重定向到已获得其自己A记录的子域:forums.example3.com。想要在.htaccess中代替DNS设置。它也应该在网址栏中显示“ forums.example3.com”。我也想这样做,以便将来可以删除重定向而无需过多的重新编码。到目前为止,我什至无法弄清楚重定向,因为每次为重定向重写此工作代码的尝试都总是失败:


    Options +FollowSymLinks -MultiViews -Indexes
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^([^.]+.)example.com [NC]
    RewriteCond %{HTTP_HOST} !^example.com$
    RewriteRule ^(.)$ http://example.com/$1 [R=301,L]
    RewriteCond %{HTTP_HOST} ^([^.]+.)example2.com [NC]
    RewriteCond %{HTTP_HOST} !^example2.com$
    RewriteRule ^(.)$ http://example2.com/$1 [R=301,L]
    RewriteCond %{HTTP_HOST} ^([^.]+.)example3.com [NC]
    RewriteCond %{HTTP_HOST} !^example3.com$
    RewriteRule ^(.)$ http://example3.com/$1 [R=301,L]
    #othersites in othersites folder
    RewriteCond $1 !^othersites/
    RewriteCond %{HTTP_HOST} ^example2.com$
    RewriteRule ^(.)$ /othersites/example2.com/$1 [L]
    RewriteCond $1 !^othersites/
    RewriteCond %{HTTP_HOST} ^example3.com$
    RewriteRule ^(.)$ /othersites/example3.com/$1 [L]

我应该添加/更改什么代码以将example3.com重定向到forums.example3.com?最好以最SEO友好的方式。

1 个答案:

答案 0 :(得分:0)

首先,此规则很可能是错误的:RewriteRule ^(.)$

一个点代表一个字符,而您通常希望允许零个或多个。

您想要的应该是RewriteRule ^(.*)$

感叹号指定否定匹配。因此,如果请求的主机是example3.com,则将符合以下规则:

RewriteCond %{HTTP_HOST} !^example.com$

但是上一个仍然会失败:

RewriteCond %{HTTP_HOST} ^([^.]+.)example.com [NC]

但是,我会编写更明确的规则,并避免不必要的否定匹配,因为它们很容易导致不良结果。

因此,以下规则足以将example3.com(带有或不带有子域)重定向到http://forums.example3.com

RewriteEngine On
RewriteCond %{HTTP_HOST} (.+\.)?example3.com$ [NC]
RewriteRule ^(.)$ http://forums.example3.com/$1 [R=302,L]

由于您说要设置临时重定向,因此可以改用HTTP代码302。