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

Wiki picture Wiki · Sep 17, 2008 · Viewed 174k times · Source

I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP?

Here is my example:

http://www.example.com/some-page.php

I want it to only be accessed through:

https://www.example.com/some-page.php

Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose...

One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version:

if($_SERVER["SCRIPT_URI"] == "http://www.example.com/some-page.php"){
  header('Location: https://www.example.com/some-page.php');
}

But that can't be the right way, can it?

Answer

Adam Rosenfield picture Adam Rosenfield · Sep 17, 2008

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();
}