Redirect From HTTPS To HTTP Using PHP

17th April 2009 - 1 minute read time

If you have a site with parts of it using SSL, but want to turn it off for mundane pages like the blog section then use the following code. This uses the $_SERVER['HTTPS'] variable to see if HTTPS is turned on, if it is then a header is issued and the page redirected.

if ($_SERVER['HTTPS'] == 'on') {
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('Location: ' . $url, true, 301);
    exit();
}

You can turn it back on again on your secure pages using the opposite.

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

Don't include both of these scripts on the same page or you will break the site! Also, make sure that no headers have been issued before hand as this code can cause a "headers already issued" error.

Comments

Permalink

Thanks for this!  

JamesCB (Wed, 08/18/2021 - 16:05)

Add new comment

The content of this field is kept private and will not be shown publicly.