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

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


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 OnRewriteCond %{HTTPS} offRewriteRule (.*) 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 requestsif ($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.