How can a user be redirected to a specific URL when entering a non-existent page?

When a user enters a non-existent page on a website, they are typically shown a generic 404 error page. To redirect the user to a specific URL instead, you can use PHP to check if the requested page does not exist and then perform a header redirect to the desired URL.

<?php
$request_uri = $_SERVER['REQUEST_URI'];

// Check if the requested page does not exist
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $request_uri)) {
    header("Location: https://example.com/redirect-url");
    exit();
}
?>