Adding canonical URLs for your website is an important part of good SEO. In this post, we’ll update you about several adding canonical tag via htaccess file and different ways for removing and adding the www
prefix, apart from that we will let you know how to remove any index.php
appendage from all URIs.
To add these code snippets, you need .htaccess file in your website root directory. Please make sure to take backup of .htaccess before adding any code.
Table of Contents
TIP : Best way take backup is either download .htaccess file or renaming the existing one with .bak and the creating a new .htaccess file.
How to remove www from all URLs : Canonical Tag via htaccess file
This code of .htaccess removes the www prefix from all URLs:
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]
</IfModule>
Replace example.com
with your domain name.
Require www for all URLs : Canonical Tag via htaccess file
This code of .htaccess adds the www prefix to all URLs:
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
</IfModule>
Replace example.com
with your domain name.
Remove the index.php from all URLs : Canonical Tag via htaccess file
This code of .htaccess strips the index.php
to all URLs:
<IfModule mod_rewrite.c>
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php\ HTTP/
RewriteRule ^(([^/]+/)*)index\.php$ https://example.com/$1 [R=301,L]
</IfModule>
Replace example.com
with your domain name.
How to remove www and index.php : Canonical Tag via htaccess file
Here is an example of how to remove www and index.php:
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php\ HTTP/
RewriteRule ^(([^/]+/)*)index\.php$ https://example.com/$1 [R=301,L]
</IfModule>
Notes
If you get a 500 server error for any of the above techniques, try replacing [R=301,L]
with [R,L]
, it will work.
So that’s all folks, let us know how it works in comment section. Connect with our developer here in case something goes wrong.
Happy Coding!