Redirect non-www to www

You have worked hard on your web application and now its time to go live with it. I presume that your first step was to buy domain name for your web application, then you should consider where to host your application. Lets assume that you have some VPS (Virtual Private Server) or Dedicate Server, then you point domain to IP address of your server and that’s is, you hooked domain with server. Next setup virtual host on Apache for domain and you are ready to go.

But what is wrong, you could get in situation that your website appear on both urls http://www.example.com and http://example.com and that could be the problem.

Google and other search engines see both domains as a different sites but with same, duplicated content, which can be terrible for your SEO ranking and can drop your site relevance big time. A bit better scenario will be that your non-www domain is not found, 404 page. We need to solve this situation, or non-www url of our site to redirect to www domain. But question is, how we do that?

There is a couple of way to accomplish this. You can do simple PHP redirection:

if($_SERVER['SERVER_NAME'] == 'example.com')
{
    header('Location: http://www.example.com');
}

But if we want to accomplish this solution on every page, that could be a big problem.

Next solution, which is the better one it to make redirection in .htaccess  file. You need to enable mod rewrite on Apache server and add following code in .htaccess file

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

This should work fine, although sometimes there could be some trouble with Apache configuration files.

All respect to both of above solutions, but my favorite one is to make redirection directly in virtual hosts settings, where we configured virtual host for our new domain. So what we should do, just add following line of code to settings:

Redirect permanent / http://www.example.com/

This will redirect not only your home page but all pages on your domain from non-www to www url.

Let’s see full Virtual host settings:

DocumentRoot /var/www/webdev
ServerName example.com:80
Redirect permanent / http://www.example.com/

allow from all
Options +Indexes

I hope this will be useful for you, if you have better way to solve this, please write.

 

No related posts.

7cdfe789e93b73e32b7a1d0b6e2e28b7

15. April 2012 by admin
Categories: PHP | 1 comment

One Comment

  1. hey ,

    nice post , i am also web developer

    Thanks
    Neel

Leave a Reply

Required fields are marked *

*