Canonical domain redirects with Apache Virtual Hosts

There are plenty of reasons you might have multiple domains pointing to the same site. In addition, it’s usually wise to configure your site so that it’s available at both domain.com and www.domain.com. But it’s usually a good idea to make sure all of these domain variations point to one proper, canonical domain.

There are a number of ways to set up canonical redirects in Apache. The most popular is probably using .htaccess, but you can also use Virtual Hosts. I prefer that method because it lives outside the web root, so other developers on my team are less likely to tamper with it. Here’s how you do it:

<VirtualHost *:80>
 ServerName www.domain.com
 ServerAlias domain2.com
 ServerAlias www.domain2.com
 RedirectMatch permanent ^/(.*) http://domain.com/$1 
</VirtualHost>

<VirtualHost *:80>
 ServerAdmin webmaster@localhost
 ServerName domain.com

DocumentRoot /var/www/domain.com/public_html
# continue configuring your site here

In this example www.domain.com, www.domain2.com, and domain2.com will all redirect to domain.com, which is the primary or canonical location of your site. After the ServerName line in the first block you can put in as many ServerAlias lines as you want, and they’ll all forward to the domain that you specify in the RedirectMatch line.

Note that if you have www in the domain of a WordPress site and you follow these instructions to remove the www, you will get a redirect loop. Instead, update your WordPress config first, and then update the virtual host config.