Permanent redirect to https by using .htaccess

Category : Optimization

The following code will help you in redirecting your website to https://www.domainname.com

This will also solve the canonical domain name issue which is good in terms of SEO too.

The following code has to be copied in your .htaccess file lying in the root directory. If not, create on and paste the below code


RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php
RewriteRule ^index\.php$ / [L,R=301]
Options -Indexes

In case your website is on WordPress CMS then follow this tutorial : https://www.basezap.com/force-https-for-wordpress-websites-by-htaccess/