Apache redirecting www to no-www

Every time I have to configure apache to host a new website, there is always a small SEO voice in my head asking me:

Did you create a www alias pointing to the website?

So let's go satisfy this little voice together.

Let's say our brand new url is http://example.com. We want to configure apache to redirect from http://www.example.com  to our new url. 

There are many solutions for that out there, but today I would like to share with you my favorite one.


A common way to solve this problem is to use the RewriteEngine and regular expressions. Regular expressions are powerful indeed, but their syntax is complicated and hard to remember. Regex are also cpu hungry and it's good practice to avoide them when possible.

To create the alias, we make use of the apache Redirect Directive:

# live url
<virtualhost *:80>
    ServerName example.com
    DocumentRoot /var/websites/example.com/public
</virtualhost>

# alias
<virtualhost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com
</virtualhost>

Redirect permanent will respond with a 301 redirect, pointing to the chosen address. Easy right? 

What about you? 

How do you manage dealing with domain name redirects in your projects?

[credits]