There are several scenarios in which you may want to redirect all your website visitors to a single, primary domain in Apache:

  • Redirect the www and non-www (root domain) hostnames of your domain to avoid duplicate content and improve SEO
  • Redirect an old domain to a new domain, maintaining links and search engine reputation
  • Redirect secondary domains (e.g. “spelling mistake” domains, or alternative-spelling domains) to your primary domain

I have recently implemented the following on my own website, and I would like to share this Apache trick.

This configuration works in Apache 2.4 with the rewrite module (mod_rewrite) enabled. It can go in the main server configuration file, a virtual host configuration file, or a .htaccess file (if the Rewrite directives are allowed.

RewriteEngine on
RewriteCond %{SERVER_NAME} !=www.andyheathershaw.uk
RewriteRule ^ https://www.andyheathershaw.uk%{REQUEST_URI} [END,NE,R=permanent]

Let’s dissect this line-by-line.

RewriteEngine on

This directive simply tells Apache to enable the rewrite module.

RewriteCond %{SERVER_NAME} !=www.andyheathershaw.uk

RewriteCond adds a condition to the next rewrite rule the module sees. In our case, we are only applying the rewrite rule if the hostname (the DNS name in the URL used to access the site) does not match our primary domain (www.andyheathershaw.uk for my website.)

RewriteRule ^ https://www.andyheathershaw.uk%{REQUEST_URI} [END,NE,R=permanent]

The final directive is the rewrite rule itself – it instructs the server to respond to the browser with a permanent redirect (also known as a 301 redirect, after the HTTP code used to indicate a permanent redirect) to https://www.andyheathershaw.uk.

In this rule, you will notice the use of %{REQUEST_URI}. This placeholder includes anything after the hostname in the URL, and ensures if your visitor accesses a page using a secondary (or old) domain, they will still find the same page on the primary domain, instead of your homepage. This provides a seamless transition for your visitors.

E.g. if you visit www.andys.eu/contact (andys.eu is a secondary domain of mine), you will be redirected to https://www.andyheathershaw.uk/contact – i.e. the contact page on the correct domain.

This also works if you visit the non-www version of my website – e.g. http://andyheathershaw.uk/blog will get you to https://www.andyheathershaw.uk/blog!

Virtual hosts, ServerName and ServerAlias

If you add the above configuration to a “virtual host”, you need to ensure any secondary domains (both www and non-www versions) are included in the virtual host configuration with a ServerAlias directive.

ServerName should be set to your primary domain.

My virtual host configuration looks like this:

ServerName www.andyheathershaw.uk
ServerAlias andyheathershaw.uk
ServerAlias www.andys.eu
ServerAlias andys.eu

Did you find this tip useful? Let me know in the comments, and I may write up some more!