Skip to content
PHP Logo

How can PHP be used to dynamically generate a redirect link based on the old URL during a server migration?

During a server migration, old URLs may need to be redirected to new URLs to maintain SEO and user experience. This can be achieved using PHP by creating a script that checks the old URL and dynamically generates a redirect link to the corresponding new URL.

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

// Define an array mapping old URLs to new URLs
$url_mapping = array(
    "/old-url-1" => "/new-url-1",
    "/old-url-2" => "/new-url-2",
    "/old-url-3" => "/new-url-3"
);

// Check if the old URL exists in the mapping and redirect if found
if(array_key_exists($old_url, $url_mapping)) {
    $new_url = $url_mapping[$old_url];
    header("Location: $new_url", true, 301);
    exit();
}
?>