How to set up correct HTTPS redirection?

HTTPS redirection

Moving your website to secure HTTPS connection is a good idea, but it may create some errors as some content is still served from HTTP or redirects to HTTPS incorrectly. In this article, you will learn how to set up correct HTTPS redirection for your website.

To use HTTPS on your website, you need a certificate from a Certificate Authority (CA). I use Let`s Encrypt SSL certification for my project. I will not describe how to purchase an SSL certificate. If you need more details on that, please refer to your hosting provider’s support documentation or help center. I also use WordPress as a content management system and I will describe the relevant details for this platform.

First step – 301 redirection using .htaccess modification:

As you probably know SSL certificates only work on one domain (example.com). Your domain`s URL – with the www prefix (www.example.com) – is a different address. To solve this issue and redirect all requests to the correct URL simply edit the .htaccess file in the main directory of your website.

Please find the .htaccess file in the directory where WordPress has been installed and open it. It usually has a name like htdocs or public_html and you will see wp-content, wp-admin and wp-includes folders in this directory. You can use the cPanel File Manager to open and edit the .htaccess file (most hosting services have this feature).

Please find <IfModule mod_rewrite.c>  row in the .htaccess file and add following code:

RewriteCond %{HTTPS} !^on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

NB! Please change example.com to your correct domain name and ensure that RewriteEngine On is also added between <IfModulemod_rewrite.c>  and </IfModule>.

As an example, I will provide code that I use (code in bold is added):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTPS} !^on [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

</IfModule>

Second step – Check http/https redirects

Please go to https://redirect.miljonivaade.eu, input your domain`s URL and click on Submit Query button. Ensure that everything is green. Correct any flagged errors.

URL to check

That’s it! Now your HTTPS redirection should work.