301 Redirect for index & non-www to www using .htaccess

301-redirect

Search engines treat website with index.html, with non www and with www pages as three different websites. This causes search engines to index three copies of a same webpage which may leads to duplicate content issue. So you need to choose one page and permanently redirect others to it. Permanent redirect also called as 301 redirect is the best way to overcome this issue.

301 Redirection Using .htaccess File for Apache Web Server

 

Create a .htaccess file and add the following code:

 

Redirecting  non-www to www (root)

Options +FollowSymLinks 
RewriteEngine on

RewriteBase /

RewriteCond %{http_host} ^example.com$ [nc]

RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc,L]

 

Redirecting index.html to www (root)

Options +FollowSymLinks 
RewriteEngine on

RewriteBase /

RewriteCond %{THE_REQUEST} ^.*\/index\.html\ HTTP/

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

 

Redirecting index.php to www (root)

Options +FollowSymLinks 
RewriteEngine on

RewriteBase /

RewriteCond %{THE_REQUEST} ^.*\/index\.php\ HTTP/

RewriteRule ^(.*)index\.php$ http://www.example.com/$1 [R=301,L]

 

Redirecting index.html and non-www to www (root)

Options +FollowSymLinks 
RewriteEngine on

RewriteBase /

RewriteCond %{THE_REQUEST} ^.*\/index\.html\ HTTP/

RewriteRule ^(.*)index\.html$ /$1 [R=301,L]

RewriteCond %{http_host} ^example.com$ [nc]

RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc,L]