tanGee
tanGee

Reputation: 573

.htaccess 301 redirect one subdomain to another, for multiple TLDs

I want to change a subdomain of my site and would like to make the RewriteRules I use to 301 users more simple, as currently I have to have multiple rules to cover various eventualities.

Is there a way that with one rule I can do the following:

subold.domain.com -> subnew.domain.com
subold.domain.co.uk -> subnew.domain.co.uk
subold.domain.local -> subnew.domain.local
subold-staging.domain.com -> subnew-staging.domain.com
subold-staging.domain.co.uk -> subnew-staging.domain.co.uk
subold-staging.domain.local -> subnew-staging.domain.local

So basically, I need to detect the presence of subold in the host, change this to subnew and redirect to this new subdomain, preserving whichever TLD the user tried to access.

At the minute, my rules are as follows:

RewriteCond %{HTTP_HOST} ^subold.domain.local [NC]
RewriteRule ^(.*)$ http://subnew.domain.local/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^subold-staging.domain.local [NC]
RewriteRule ^(.*)$ http://subnew-staging.domain.local/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^subold.domain.com [NC]
RewriteRule ^(.*)$ http://subnew.domain.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^subold-staging.domain.com [NC]
RewriteRule ^(.*)$ http://subnew-staging.domain.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^subold.domain.co.uk [NC]
RewriteRule ^(.*)$ http://subnew.domain.co.uk/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^subold-staging.domain.co.uk [NC]
RewriteRule ^(.*)$ http://subnew-staging.domain.co.uk/$1 [L,R=301]

Upvotes: 1

Views: 1373

Answers (1)

anubhava
anubhava

Reputation: 785256

Assuming there is just a difference of subold vs subnew in your real domain names.

You can have just one rule like this:

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

Upvotes: 2

Related Questions