Redirect Apache ServerAlias to ServerName

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.

 

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.