Redirect a site to HTTPS using PHP

Written by Yujin Boby

Edit in WordPress

This PHP script will redirect website visitors to HTTPS (SSL) URL. You can add this in your index.php of the website

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on" ) {
    header("HTTP/1.1 301 Moved Permanently");
    $newUrl = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    Header("Location: $newUrl");
    exit;
}

To redirect visitors to a new URL using PHP, use the following PHP code

$newUrl = "https://NEW-URL-HERE" . $_SERVER['REQUEST_URI'];
header("HTTP/1.1 301 Moved Permanently");
Header("Location: $newUrl");
exit;

You can also use Apache mod_rewrite .htacess to do the redirection.