Fix Canonical URL using .htaccess

When you host a web site, many web hosting providers allow your web site access using multiple urls like yourdomain.com, www.yourdomain.com. If you have a dedicated IP address, your web site become available on the IP address also. It is bad for SEO to have a site available in multiple URLs. If search engine index your web site contents using differnt URLs, that will affect your page ranking.

To ge beter search ranking, you need to deicde which URL you want search engines to index. This can be with www or with out www, it is more of a personal choice. In my case, i decided to use with out www (https://serverok.in) to make URL shorter. Once you decided the URL you need google to index, you need to redirect all other URLs used to access your web site to this URL. This is called Canonical url.

On Apache web server, you can do this using .htacess file. Create an .htaccess file with following content

In above code, replace www.yourdomain.com with the Canonical URL of your web site. If you don’t use www, then remove the www from the redirect code. What the code doing is check if visitor is using proper Canonical URL to access your web site, if not redirect it to Canonical url. In third line, we redirect to https, if you don’t have SSL installed, change it to “http” instead of “https”.

See redirect

Leave a Reply

Your email address will not be published. Required fields are marked *