URL rewrite with www prefix using htaccess

At many times we are in need to append www prefix in website urls. This post will guide you to achieve the same.

Lets say we have a domain example.com and we want it to appear as www.example.com or http://www.example.com. In order to complete this we must have a file with the name .htaccess placed in the root directory of the website with the following code:

URL rewrite with www prefix using htaccess

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

Please replace example.com with your domain name and you are done. Save your .htaccess file and clear your browsers cache in case you face any issues.

Note*: This will work on servers supporting .htaccess e.g. Apache Server.

Good Luck!

Related Post

Advertisements

Yuvraj has written 39 articles

"Learn & Share" - I believe in this. What about you?

  • it help a lot. Is there anyway to do this in opposite way. I mean if any visitor come to http://www .example. com it automatically redirects it to http:// example. com.

  • admin

    Thanks for sharing your concerns.
    Please post your questions in our forum.

    Thanks

  • Jhon

    In addition to above the below code handles redirect of index.html to root :

    RewriteEngine On
    RewriteBase /
    RewriteCond %{http_host} ^website\.com [NC]
    RewriteRule ^(.*)$ http://www.website.com/$1 [R=301,NC]
    RewriteRule ^(([^/]+/)*)index\.html?$ http://www.website.com/$1 [R=301,L]
    
  • Redirect from .html to .php without showing .php in browser address bar.

    RewriteRule ^index.(php|html)$ / [R=301,L]

    RewriteRule ^(.*).html$ $1.php

    • makemypost

      Thanks for sharing the above piece of code. Its really very useful.

  • MakeMyPost

    RewriteEngine On

    RewriteBase /

    RewriteCond %{http_host} ^website.com [NC]

    RewriteRule ^(.*)$ http://www.website.com/$1 [R=301,NC]

    RewriteRule ^(([^/]+/)*)index.html?$ http://www.website.com/$1 [R=301,L]