How to redirect from HTTP to HTTPS?

As you probably noticed, more and more pages are serving content through the HTTPS protocol. The green padlock icon is almost always visible. You should also know that Google gives higher ranking to the HTTPS served pages. Even if you think that there is nothing important on your website, you should switch to HTTPS. SSL certificate can now be obtained freely via Let’s encrypt so there are no excuses.

HTTP to HTTPS in Apache

Currently recommended way of redirecting is an adjustment to the server configuration file. In the configuration of the particular virtual host in Apache, you should use these:

<VirtualHost *:80>
    Redirect "/" ""

<VirtualHost *:443>
    # and the rest of SSL configuration goes here

If you have no access to the Apache configuration, but you can alter .htaccess file for your website, you should use this approach:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This is “an old way” but is still working fine.

But I’m using IIS on Windows, what can I do?

In such case, you probably already have web.config file in the root of your website structure. If not, create one and place this code inside:

				<rule name="HTTP to HTTPS redirect" stopProcessing="true">
					<match url="(.*)" />
						<add input="{HTTPS}" pattern="off" ignoreCase="true" />
					<action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />

Please note that if you already have web.config in place, you will probably need to copy only part of the above configuration.

What if I’m able to adjust PHP only?

Here you are, you can use this tiny function:

function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];