Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force users to access my page over HTTPS instead of HTTP?

People also ask

Can you switch HTTP to HTTPS?

On the surface, changing from http to https is pretty straightforward: Purchase an SSL certificate, Install your SSL certificate on your website's hosting account, Make sure that any website links are changed from http to https so they are not broken after you flip the https switch, and.

What does it mean to force HTTPS?

Select Enable Force HTTPS. This will redirect website users to HTTPS. As long as the website has an SSL certificate and all content loads via HTTPS, the site should show as secure.


The way I've done it before is basically like what you wrote, but doesn't have any hardcoded values:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

You could do it with a directive and mod_rewrite on Apache:

<Location /buyCrap.php>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Location>

You could make the Location smarter over time using regular expressions if you want.


You should force the client to request HTTPS always with HTTP Strict Transport Security (HSTS) headers:

// Use HTTP Strict Transport Security to force client to use secure connections only
$use_sts = true;

// iis sets HTTPS to 'off' for non-SSL requests
if ($use_sts && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
    header('Strict-Transport-Security: max-age=31536000');
} elseif ($use_sts) {
    header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true, 301);
    // we are in cleartext at the moment, prevent further execution and output
    die();
}

Please note that HSTS is supported in most modern browsers, but not universal. Thus the logic above manually redirects the user regardless of support if they end up on HTTP, and then sets the HSTS header so that further client requests should be redirected by the browser if possible.


I just created a .htaccess file and added :

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Simple !


// Force HTTPS for security
if($_SERVER["HTTPS"] != "on") {
    $pageURL = "Location: https://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    header($pageURL);
}