views:

35

answers:

3

What I'm trying to accomplish with htaccess mod-rewrite:

Redirect all sub-domains to new domain name w rewrite rule.

e.g.

test1.olddomain.com ===> test1.newdomain.com

test2.olddomain.com ===> test2.newdomain.com

test3.olddomain.com ===> test3.newdomain.com

This is what I have so far which of course is wrong:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^olddomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$ [NC]
RewriteRule ^(.*) http://www.newdomain.com/$1 [R=301,L]

RewriteRule [a-zA-Z]+\.olddomain.com$ http://$1.newdomain.com/ [R=301,L]

Since I'm not a Regular Expression junkie just yet, I need your help... Thanks for any help you can give here. I know also we can compile these first two conditions into one.

Note: The reason I don't redirect all domain using DNS is that a lot of directories need special rewrite rules in order to maintain positions on SEO.

A: 
RewriteRule ^(.+)\.olddomain\.com$ http://$1.newdomain.com/ [R=301,L]

You need to specify the ^ at the beginning to ask the regex engine to match a line beginning there. Next, you match anything before ".olddomain.com" and assign that to the first matched pattern (which will later be accessible in $1). You need to surround with parentheses (.+) in order for the match to be assigned to $1.

Roadmaster
+1  A: 

In .htaccess files, the "URL" that RewriteRules match has been stripped of the domain name and any directories that led to the current directory. (Using mod_rewrite in .htaccess files is a huge pain; if you have access to the server conf do it there instead!!)

So, assuming that your .htaccess is in your DocumentRoot, try something like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)olddomain\.com$ [NC]
RewriteRule ^(.*)$ http://%1newdomain.com/$1 [R=301,L]

The %1 is supposed to match the first group in the RewriteCond and the $1 is supposed to match the URL part.

Artelius
Thanks, this worked perfectly.
Codex73
I'm shocked, probably the first time I get a mod_rewrite right first try without testing!
Artelius
A: 

Its now working for me dude. I need the same thing as him.

this is what i posted

RewriteCond %{HTTP_HOST} ^(.*)sio-india\.com$ [NC] 
RewriteRule ^(.*)$ http://%1sio-india.org/$1 [R=301,L] 
Ali