Introduction: Redirecting your website to a URL with ‘www’ is a common practice for standardizing the domain format. In this guide, we’ll walk you through a simple PHP code snippet that accomplishes this redirection, ensuring a consistent and user-friendly URL structure.
PHP Code for www Redirection: To redirect a site to a URL with ‘www’ using PHP, add the following code snippet to your index.php
file or another file included by index.php
:
<?php
$domainName = $_SERVER['HTTP_HOST'];
if (strpos($domainName, 'www') === false) {
header("HTTP/1.1 301 Moved Permanently");
$urlNew = 'https://www.' . $domainName . $_SERVER['REQUEST_URI'];
Header("Location: $urlNew");
exit;
}
?>
Explanation:
- Retrieve the current domain name from the server request.
- Check if the domain contains ‘www’. If not, proceed with the redirection.
- Send a 301 Moved Permanently header to indicate a permanent redirect.
- Form the new URL by adding ‘www’ to the current domain and append the requested URI.
- Use the
header
function to set the new location for the redirect. - Terminate the script execution using
exit
.
Copy and paste the provided PHP code into your index.php
file or another file included by index.php
. Upon accessing your website without ‘www’, visitors will be automatically redirected to the ‘www’ version of the URL, promoting a standardized and consistent web presence.
Note: Ensure that your server supports PHP and that the necessary permissions are in place for this redirection to work as intended. For additional tutorials and guides on web development, PHP, and more, visit TutoSquad. Unlock a wealth of knowledge to enhance your coding skills and stay updated with the latest tips and tricks.