Redirect on Apache Server

This short tutorial will explain how to redirect a non www web page to a www web page. This method only works for an Apache server.

www vs. no www

Search engines, including Google, recommend using www or not www but not both. In other words, use www.mydomain.com or mydomain.com. This little trick prevents search engines from indexing web pages twice and possibly causing duplicate content issues.
Using a 301 permanent redirect can alleviate the problem. To redirect mydomain.com to www.mydomain.com do the following:

In an existing .htaccess file or a new .htaccess file add the following code:

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

Replace mydomain with the domain you want to redirect. r=301 means redirect the client and send a status code of 301.

Example

For the domain smartlabsoftware.com

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^smartlabsoftware.com [nc]
rewriterule ^(.*)$ http://www.smartlabsoftware.com/$1 [r=301,nc]

No www

For those who want to retain their domain without the leading www this example will redirect www.mydomain.com to mydomain.com

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^www.mydomain.com [nc]
rewriterule ^(.*)$ http://mydomain.com/$1 [r=301,nc]

Test it Out

Test out the change by typing in mydomain.com - it should show up as www.mydomain.com.
mydomain.com should show up as a 301 permanent redirect

Related resources