使用.htaccess重定向主域但不是某些子域

时间:2013-06-02 19:26:26

标签: apache .htaccess redirect

目前我有:

Redirect 302 / http://www.example.com

虽然我仍然希望这种重定向发生,但如果他们在此子域上说foo.mydomain.com或任何其他页面,我不希望它重定向。

我该怎么做?

1 个答案:

答案 0 :(得分:18)

要以这种方式更具体,您需要使用RewriteCond / RewriteRule而不是简单的Redirect指令。为!执行否定匹配(foo.mydomain.com)并执行重写。您可以将多个子域与OR组(foo|other1|other2)

匹配
RewriteEngine On
# Redirect anything except foo.example.com, bar.example.com
RewriteCond %{HTTP_HOST} !^(foo|bar)\.example\.com$ [NC]
# Redirect to www.example.com, preserving the URI
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=302]

如果您只想重定向到根目录而不是通过$1附加整个URI,请使用相同的RewriteCond,然后执行:

# Match and redirect everything to the root of www.example.com
RewriteRule ^. http://www.example.com/ [L,R=302]