user121196 user121196 - 2 months ago 15
Apache Configuration Question

apache redirect from non www to www

I have a mortgage calculator site that doesn't seem to redirect from mookal.com to www.mookal.com

My apache config is as follows:

RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.mookal.com [nc]
RewriteRule ^(.*)$ http://www.mookal.com/$1 [r=301,nc]


What am I missing?

Answer

Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

And then you'll have another <VirtualHost> section with ServerName www.example.com for your real server configuration. Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).