When we talk about web development and website creation online, there are many things that we need to consider before moving forward to build websites online and the most important thing is redirection i.e., redirection like redirecting www to non-www  or vice versa. This is the most sensitive thing that should be fixed when setting up a website. In this way, I’ve written this article to help people properly redirect www to non-www via .htaccess file in Apache based servers.

This is the most far easy way to force a website users to use the www or non-www version of your site. It is also important in order to prevent duplicate content in search engines. That’s why we must consider redirecting users to use either the www or the non-www version of your website domain.

Note: You can either force your website users to www version of your site or non-www version using .htaccess file. If you are using WordPress then you can edit .htaccess file from WordPress dashboard or you can use FTP client to edit .htaccess file.

Redirect non www to www or vice versa

Redirect non www to www or vice versa

Properly Redirect www to non-www or Vice Versa

1. Force users to use http://www.yoursite.com

The following code will force your users to use the www version of your site to access all of the content that is present in your site. Just copy and paste this code in your .htaccess file and change the domain name to your domain name from the code:

# Redirect www urls to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.yoursite\.com [NC]
RewriteRule (.*) http://yoursite.com/$1 [R=301,L]

2. Force users to use http://yoursite.com

Or if you want to redirect your website users to non-www version of your site to access all of the content of your site. Paste the following code in your .htaccess file and change the domain name to your domain name from the code:

# Redirect non-www urls to www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite\.com [NC]
RewriteRule (.*) http://www.yoursite.com/$1 [R=301,L]

Conclusion

That’s how we do this. For any question comment below.

Image credits: raymondware.com