Redirect From HTTPS To HTTP Using PHP

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

Thanks for this!  

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.