Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Redirect Subdomains to Other Domain

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.

like image 233
Codex73 Avatar asked Nov 20 '25 18:11

Codex73


1 Answers

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.

like image 161
Artelius Avatar answered Nov 23 '25 06:11

Artelius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!