What is the best way to handle redirection based on the host in PHP?

When handling redirection based on the host in PHP, you can use the $_SERVER['HTTP_HOST'] variable to get the current host name and then compare it against the desired host name. If they do not match, you can use the header() function to redirect the user to the correct host.

$current_host = $_SERVER['HTTP_HOST'];
$desired_host = 'example.com';

if ($current_host != $desired_host) {
    header('Location: https://' . $desired_host . $_SERVER['REQUEST_URI']);
    exit();
}