For SEO purposes this is good practice to keep your website URLs either with www or without www only. In this tutorial, you will learn how to force a redirect to www or non-www URL only. 301 status code tells search engines that the page has permanently moved to a new location.
Force Redirect to WWW or Non-WWW
Login to server with admin privileges and navigate to document root of your website. Now create a .htaccess file using one of below content as per your requirements.
Force 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]
Force 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 following settings under your domains VirtualHost.
<VirtualHost *:80> [...] <Directory "/home/user/public_html"> Allowoverride all </Directory> [...] </VirtualHost>
Enable Apache Rewrite Module
Also make sure Apache rewrite module is enabled. If not use the following command to enable module.
sudo a2enmode rewrite
Leave a Reply