For SEO purposes this is good practice to keep your website URLs either with www or without www. The .htaccess
provides you an easy way to implement the redirections using Apache rewrite modules. Apache reads the .htaccess and followed its rules on every request. So remember that the server will take a bit more time for request processing.
In this tutorial, you will learn how to redirect to www or non-www URL only. 301 status code tells search engines that the page has permanently moved to a new location.
Redirect to WWW or without WWW
Login to server with admin privileges and navigate to document root of your website. Now create a .htaccess file using one of the below content as per your requirements.
Redirect non-www to www
This will force URL as www.example.com, this will always add www in URL either you accessed it with or without www.
RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
Redirect www to non-www
This will force URL as example.com, this will always remove www from URL, you either accessed it with or without www.
RewriteEngine on RewriteCond %{HTTP_HOST} ^www.example.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]
Enable .htaccess to Work
Before using .htaccess, make sure your .htaccess is enabled to use in Apache. To enable this add the following settings under your domains VirtualHost.
<VirtualHost *:80> [...] <Directory "/home/user/public_html"> Allowoverride all </Directory> [...] </VirtualHost>
Enable Apache Rewrite Module
Also make sure the Apache server have rewrite module enabled. If it is not already enabled, use the following command to enable module on Debian based systems.
sudo a2enmode rewrite
Conclusion
In this write-up, you have learned the .htaccess rules to redirect a domain from www to non-www, and vice versa.