Redirect Visitors to a Different Web Page

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’);

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(“Location: $url”);

Include your sitefunction.php and then call reDirect()

{code type=php}


Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the