Thursday, 3 October 2013

Redirecting all traffic to add www prefix with Apache

It may be useful to add the "www." prefix automatically for all traffic if your visitors are not typing them. With Apache you need to have mod_rewrite enabled to use this method.

1. Allow mod_rewrite override for your current website. Go to your site configuration file (located at /etc/apache2/sites-enabled/000-default if you are using Ubuntu) and add the following lines into the <VirtualHost *:80> section:
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order allow,deny
    allow from all
</Directory>
2. Go to your document root (e.g., /var/www), create a new file named .htaccess and with the following content:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
That's it. Restart Apache and it should work by now.

No comments:

Post a Comment