Redirect Visitors to a Different Web Page

Last Updated on: May 16, 2026

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 the first search result
  • Moving to a different domain name

In any of these scenarios, you can use a PHP script to redirect the visitor to another page of your choice e.g. 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:

<?php header('Location: /index.php'); ?>

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:

<?php
echo "Hello World!";
header('Location: /index.php');
?>

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:

function reDirect($num, $url) {
    static $http = array(
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed"
    );
    header($http[$num]);
    header("Location: $url");
}

Include your sitefunction.php and then call reDirect()

<?php
@include('/sitefunction.php');
reDirect(404, '/brokenlink.php');
?>

It is worth knowing which status code to send with a redirect. A 301 tells browsers and search engines that the move is permanent, so use it when a page has retired for good or you have moved to a new domain. A 301 passes on most of the old page’s search ranking, which matters if the page had any traffic. A 302 says the move is only temporary, which is what you want for site maintenance or a page that is briefly unavailable. The first header() example above sends no status code at all, so set one explicitly whenever the redirect is meant to last.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *