Redirect Visitors to a Different Web Page
Last Updated on: March 7, 2011
Sometimes it is necessary to divert a visitor to a different page on your website or even an external site. This might be for a variety of reasons:
- Site maintenance
- Page retirement
- Incorrect URL
- Site busy or failed
- Automatically jump to first search result
- Moving to a different domain name
In any of these scenario’s you can use a PHP script to redirect the visitor to another page of your choice – maybe the home page or a standard maintenance or error page.
The easiest way is to use the header() function to do the work. The following example would redirect to the index.php page of your website:
{code type=php}<? header(‘Location: /index.php’); ?>{/code}
One thing to watch out for is that you must use header() before any output is sent, whether that is from normal HTML tags, empty lines in a file or PHP. Any output, including empty spaces will stop the redirect from working. This is an example of this method that will not work:
{code type=php}<?php
Echo “Hello World!”;
Header(‘Location: /index.php’);
?>{/code}
A more complicated example creates a function called reDirect() in your sitefunction.php. This is a cut down example that will need expanding for all the HTTP error codes:
{code type=php}Function reDirect($num,$url){
Static $http = array(
404 => “HTTP/1.1 404 Not Found”,
405 => “HTTP/1.1 405 Method Not Allowed”
);
header($http[$num]);
header(“Location: $url”);
}{/code}
Include your sitefunction.php and then call reDirect()
{code type=php}
<?php
@include(‘/sitefunction.php’);
reDirect(404,’/brokenlink.php’);
?>
{/code}