Wednesday, February 20, 2013

Configuring Apache and DNS to access site without www prefixawesomehost.com

When hosting a site, it's convenient to just type the domain name e.g. mydomain.com instead of pre-fixing it with www.  This can be easily configured using Apache and by adding one additional entry to the DNS.  For this article's purpose, we'll be using awesomehost.com as the domain.

To start off with, add a new A DNS entry to point to the same IP as the A entry which maps to www.awesomehost.com.  You'll have something like below:

Name Type Value
awesomehost.com A 192.168.0.1
www.awesomehost.com A 192.168.0.1

Once that's done, we configure Apache.  Inside the VirtualHost directive, add the Alias directive as well as the rewrite condition:

<VirtualHost *:80>
ServerName awesomehost.com
ServerAlias www.awesomehost.com

DocumentRoot /home/blah/public_html
        <Directory /home/blah/public_html/>
AllowOverride All
Order allow,deny
allow from all
        </Directory>

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

</VirtualHost>


The rewrite condition redirects all requests beginning with www to the domain without www prefix.




No comments: