Apache accept CNAME redirect

apache-2.2domain-name-system

I have a domain, let's say mydomain.com. I'd like to redirect www.mydomain.com to the naked domain, mydomain.com. So I set up the following DNS. (The IP is just for show)

A        mydomain.com    192.168.0.1
CNAME    www             mydomain.com

What happens though, is that Apache serves my default site (which is empty), rather than the mydomain site. Since I'm hosting multiple domains, I have:

/etc/apache2/sites-available/default
/etc/apache2/sites-available/mydomain
/etc/apache2/sites-available/myOtherDomain
/etc/apache2/sites-available/yetAnother

The start of /etc/apache2/sites-available/mydomain looks like this:

<VirtualHost *:80>
    ServerAdmin sample@email.com
    ServerName mydomain.com
    ServerAlias mydomain.com

What's wrong with this setup that's it's not redirecting www.mydomain.com to mydomain.com? Thanks for your help.

Best Answer

Apache itself won't redirect for you.. You'd have to use something like mod_rewrite to do that

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com [NC]
RewriteRule ^(.*) http://mydomain.com/$1 [L,R=301]

Edited for regex syntax.

Related Topic