Redirecting to a different domain
Redirect URLs From Old To New Domain Using 301 Redirects In .htaccess
When you need to switch a website from an old domain to a new domain, you need to redirect all your page URLs, this is when htaccess is your friend.
The code below will create 301 url redirects for both the www and non-www version of ‘olddomain.com‘ to the new domain ‘newdomain.com‘.
Add this .htaccess file to the OLD site webroot and upload the files from the old site to the new to see a seamless switch from an old domain to a new one.
So the example below is redirecting all URLs from olddomain.com to newdomain.com, this is also the 301 redirect to use when using Googles Change of Address tool in Search Console.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [L,R=301,NC]
The above will use the non-www as preference.
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
The above here will redirect 301 all urls from one domain to another but give preference to the www version.
You can also apply this to a subdomain – so the example below is redirecting all URLs from subdomain.olddomain.com to subdomain.newdomain.com
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]
You can also mask a domain which is like a redirect but keeps the old domain URL but shows the remaining part of the new URL of the new domain – example …
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com
RewriteRule ^(.*) http://newdomain.com/$1 [P]