In the online world, domain redirection refers to the process of forwarding requests from one domain to another. This can be achieved through server configurations or PHP scripts. Domain redirection plays a vital role in website management. This article explores its benefits and provides specific PHP implementation examples.
When a website has multiple domains pointing to it, domain redirection ensures all visitors are directed to the primary domain. This avoids inconsistent content delivery caused by different domain entries and enhances the overall user experience.
During domain changes or temporary redirects, domain redirection guarantees that requests to old domains automatically lead to the new domain, ensuring seamless website accessibility.
For SEO, a consistent domain and URL structure is crucial. Domain redirection prevents duplicate content issues by consolidating authority to the main domain, boosting search engine rankings and site credibility.
Malicious sites might mimic legitimate domains to deceive users. Using domain redirection to forward these suspicious domains to warning or controlled pages can effectively protect users from scams and attacks.
The following PHP script demonstrates how to implement domain redirection:
<?php
$redirect_domains = [
'old-domain1.com' => 'new-domain.com',
'old-domain2.com' => 'new-domain.com',
// Add additional source and target domains here
];
$current_domain = $_SERVER['HTTP_HOST'];
if (array_key_exists($current_domain, $redirect_domains)) {
$new_domain = $redirect_domains[$current_domain];
$redirect_url = 'http://' . $new_domain . $_SERVER['REQUEST_URI'];
header('Location: ' . $redirect_url, true, 301);
exit();
}
?>
This code defines an associative array mapping source domains to target domains. It retrieves the current domain, checks if it needs redirection, and if so, constructs the redirect URL and sends a 301 permanent redirect response.
To use this script, ensure your server supports PHP and place the code in your site's root entry file (such as index.php).
Proper use of PHP domain redirection helps unify access, improves user experience, optimizes SEO, and enhances website security. It is a practical and essential technique recommended for website management.