How to redirect website from HTTP to HTTPS only with PHP

Post Reply
User avatar
isscbta
Team Member
Posts: 137
Joined: Mon Jul 19, 2021 1:41 am
Has thanked: 17 times
Been thanked: 3 times

In a scenario where you need to force the domain to use only HTTPS, but the only way to do that is through PHP, use this piece of code:

Code: Select all

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}
With WordPress you can simply add this at beginning of the wp-config.php file

Tags:
Post Reply