Course lectures : 1 of 1

Enforce 'www.' on domain name with .htaccess

Last updated: 27th October 2011

mod_rewriteapache mode_rewrite.htaccess.htaccess rewriteenforce www

Redirecting domain.com to www.domain.com is pretty straight forward and worth knowing.

When you are running your website you should decide what version you want to use - either with 'www' or without - and you should stick to it whenever you link to your site.
You might soon find out that this consistency helps you with your SEO campaign, therefore it is pretty important element of any successful website.

To create the redirect to 'www' create the .htaccess file in the root of your site and open it for editing (or open the existing one).

Now start by checking whether the mod_rewrite is enabled on your server:

<IfModule mod_rewrite.c>

</IfModule>

Now, in between these two tags type the following, replacing domain name with the one you're working on:

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

Your entire block of code should now look like this:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

If you now open your browser and navigate to the site using the domain name without www - you'll see that you will be automatically redirected to the www version of your domain.

COMMENTS

If you'd like to include code example please wrap your code within <pre><code> tags.


<pre>
<code>
function fullName(firstName, lastName)
{
    return firstName + ' ' + lastName;
}
</code>
</pre>