Guides Tutorials

Force WWW or non WWW redirection in htaccess

www or non www redirection

What is redirection?

Redirection is forwarding one URL to other URL.

Why is permanent www or non www redirection important?

When you create a blog, it can be accessed with or without www if you do not do permanent redirection to www or non www and this can lead to a penalty for duplicate content as Google or any search engine considers www and non www as different sites, it doesn’t matter if domain name is same. To avoid this penalty you need to decide whether to keep www or not and then do a permanent redirection for that in htaccess file on your server.

Below is an easy tutorial to do redirection in htaccess.

Opening .htaccess file

.htaccess is a file on your server, to open and edit you can either use your cPanel file manager or Filezilla to access .htaccess file (I am using filezilla).

Using filezilla is easy, just download and open it, use your credentials to login and in wordpress folder search for .htaccess file, now right click on that and select edit.

htaccess

To redirect from www to non www

Copy and save  any of the below code in .htaccess file to force non www version for your site.

Use any one only, keeping both in htaccess will cause error.

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

*Use your domain name in place of example . com

What this above code will do?

It will redirect

www.example.com to example.com

and

www.example.com/abc to example.com/abc

 

To redirect from non www to www

Copy and save the below code to htaccess file to force www version for your site.

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

What this above code will do?

It will redirect

example.com to www.example.com

and

example.com/abc to www.example.com/abc

Now whenever you create a site choose www or non www and always do a permanent redirection for that to stay safe.

NOTE: If you are using WordPress CMS place the code above the WordPress rules.

About the author

Harsh

I am a student blogger, interested in SEO and internet marketing.
I try to write about what all I have learnt till now.

Leave a Comment