Wildcard subdomain redirect using mod_rewrite

mod-rewrite, redirect, wildcard-subdomain

Solution

Is it possible you're falling through and catching another RewriteCond elsewhere? It looks to me like the RewriteCond in your example will never match an HTTP_HOST that ends in domain1.com due to the presence of the `!` negation prefix.

This slight modification seems to work the way you want:

RewriteCond %{HTTP_HOST} ^(.+\.)?domain1.com$ [NC]
RewriteRule ^ http://%1domain2.com%{REQUEST_URI} [R=301,L]

Problem

I am trying to figure out how to do a redirect using mod_rewrite to a new domain, that will include a wildcard subdomain redirection. I am hoping for such result: ``` domain1.com -> domain2.com domain1.com/foo/bar?baz=quux -> domain2.com/foo/bar?baz=quux www.domain1.com -> www.domain2.com www.domain1.com/foo/bar?baz=quux -> www.domain2.com/foo/bar?baz=quux sub.domain1.com -> sub.domain2.com sub.domain1.com/foo/bar?baz=quux -> sub.domain2.com/foo/bar?baz=quux *.domain1.com -> *.domain2.com *.domain1.com/foo/bar?baz=quux -> *.domain2.com/foo/bar?baz=quux ``` I was trying something like this: ``` RewriteCond %{HTTP_HOST} !^(.+\.)?domain2.com$ [NC] RewriteRule ^ http://%1domain2.com%{REQUEST_URI} [R=301,L] ``` But the `%1` which I was hoping to refer to the optional subdomain caught in the `RewriteCond` is not brought through to is completely dropped, so any requests ends up being redirected to `http://domain2.com%{REQUEST_URI}`. What am I doing wrong?

Original source