How to Redirect WWW to Non-WWW using .htaccess


redirect www to non www htaccess

Google treats the non-www and www versions of your sites as separate entities. So for SEO purposes, it is advisable to maintain only one of those versions – either www or non-www. If the non-www version of your website has many backlinks, then it might be better to redirect www to non-www version. Here’s how to redirect www to non-www using .htaccess.

 

How to Redirect WWW to Non-WWW using .htaccess

Here are the steps to redirect www to non-www using .htaccess. Basically, you need to open the .htaccess file in a text editor, add the rules given below and restart Apache server to apply changes. Before we proceed, please ensure you have enabled mod_rewrite for Apache server. Here are the steps to do it for :

  1. Ubuntu/Debian systems
  2. CentOS and similar systems

.htaccess file allows you to modify Apache settings without accessing its config file. You will find it in your website’s root folder (e.g /var/www/html). If you can’t find the file, just create a blank file called .htaccess

 

1. Open the .htaccess file

Open the .htaccess file using a text editor


$sudo nano /var/www/html/.htaccess

 

2. Add Redirect Rules

If you want to redirect www to non-www version of your website, add the following rules to your .htaccess file. Its’s a permanent redirect (301). Replace example.com with your your domain name


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

 

If you also want to force https when you redirect www to non-www,


RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

 

3. Restart Apache Server

Restart Apache Web Server to apply changes


$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

 

That’s it! Now Apache will automatically redirect www to non-www version of your website.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!