I had a website that was moved to a new domain name but I wanted to make all the old URLs redirect to the new domain.

However, redirecting using a typical .htaccess redirect as shown below wouldn’t work because it was new using the old domain as a ServerAlias to the new domain/ServerName.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

 

I found part of the solution to this here. I added in detection of HTTPS. Now whenever anyone accesses the site from a domain which isn’t example.com it will redirect to example.com including all the old URLs. I placed this in the Apache config file in the VirtualHost section for the domain rather than the .htaccess file. Replace example.com with the new domain/ServerName.

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST}  !^example.com [nocase] [OR]
RewriteCond %{HTTP_HOST}  !^www.example.com [nocase]
RewriteRule ^(.*)$        http://example.com$1 [last,redirect=301]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST}  !^example.com [nocase] [OR]
RewriteCond %{HTTP_HOST}  !^www.example.com [nocase]
RewriteRule ^(.*)$        https://example.com$1 [last,redirect=301]