Redirect Apache ServerAlias to ServerName

by | Feb 22, 2015 | Server | 0 comments

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]

Hosting Recommendation

Hostinger - The Secret Weapon of Successful Site Owners

There's a reason I recommend Hostinger. After testing dozens of hosting providers, only Hostinger delivers the perfect combination of:

🔥 Blazing-fast load times
(essential for performance)
🛡️ Rock-solid uptime
(your sites earn money 24/7)
🔒 Free SSL certificates
(builds trust instantly)
💾 Automated backups
(your business is always protected)
👨‍💻 Expert support
(problems solved in minutes, not days)
⚙️ One-click WordPress setup
(seamless integration guaranteed)
💰 Starting at just $2.99/month
(premium hosting that won't break the bank)

Use my link or referral code
MILLIONDOLLARS to get 20% off !