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

Bre*_*ett 9 apache .htaccess redirect

目前我有:

Redirect 302 / http://www.example.com
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能做到这一点?

Mic*_*ski 20

要以这种方式更具体,您需要使用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]
Run Code Online (Sandbox Code Playgroud)

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

# Match and redirect everything to the root of www.example.com
RewriteRule ^. http://www.example.com/ [L,R=302]
Run Code Online (Sandbox Code Playgroud)