One the most common uses of htaccess files is to force a users and search engines to use a specific url scheme.
If you don’t force a specific url scheme, meaning www or non www, then it’s likely you could be penalized by search engines for duplicate content.
It’s been long known that www and non-www traffic is treated as two different sources by search engines.
For example, let’s use my blog kickstartcommerce.com. Now people who find my blog to be interesting could very well link to kickstartcommerce.com with no problem.
However, the problem with this is that search engines have indexed my website as www.kickstartcommerce.com.
Not that one is right and the other is wrong, because you could use the non-www or www. The challenges arise when you use both.
Now, it’s unlikely that you can monitor, control and request that everyone that links to your website to use non-www or www when linking to your website.
But this is where htaccess files can correct incorrectly link to your website and provide proper standardization of the used domain, whether www or non-www.
This is known as the canonical web address, or said another way, the web address you would like for uses to see when visiting your website.
So, let’s say I wanted to force users to use the non-www domain when visiting my website. Here’s what my htaccess file would look like:
1 2 3 4 |
RewriteEngine on RewriteBase / RewriteCond %{HTTP_HOST} ^www.kickstartcommerce.com [NC] RewriteRule ^(.*)$ http://kickstartcommerce.com/$1 [R=301,NC] |
Now, let’s say I wanted to force users to use the www domain when visiting my website. Here’s what my htaccess file would look like:
1 2 3 4 |
RewriteEngine on RewriteBase / RewriteCond %{HTTP_HOST} ^kickstartcommerce.com [NC] RewriteRule ^(.*)$ http://www.kickstartcommerce.com/$1 [R=301,NC] |
Easy enough. Let’s say I wanted to force non-www to www when visiting my websites I’m hosting from one server without typing in the domain name. Here’s what my code in the single htaccess file:
1 2 3 4 |
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(.*)$ [NC] RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L] |
And one last htaccess rule that we can’t forget about. To force www to non www website, you’re htaccess code would look like the following:
1 2 3 4 |
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] |