301 Redirects

When redirecting a request from one page to another it's best to send a status code along with the redirect to inform browsers and search engines what's going on. HTTP 301 redirects refer to pages that have been moved permanently and so sending this status code when redirecting users to new pages will preserve your search engine rankings and keep visitors on your website.

The PHP code

By default the PHP header() function will set a 302 Found status code which informs the client the webpage has been moved temporarily.

<?php
header
("Location: /newpage.html"); // redirects to newpage.html with 302 HTTP code
?>

In order to override the default HTTP status code we send another header before the redirect:

To redirect to another page using PHP and a 301 status use the following code:

<?php
header
("HTTP/1.1 301 Moved Permanently"); // sets HTTP status code to 301
header("Location: /newpage.html"); // redirect to newpage.html
?>

Simply replace newpage.html with whatever page or URL you wish to redirect to and that's it - 301 redirects in a nutshell!

Remember that the header calls must be made before any output - unless a buffer is used. The code below will fail:

<html>
<?php
header
("HTTP/1.1 301 Moved Permanently"); // sets HTTP status code to 301
header("Location: /newpage.html"); // redirect to newpage.html
?>

Using ob_start() and ob_end_flush() will stop the error by buffering the output:

<?
ob_start
();
?>
<html>
<?php
header
("HTTP/1.1 301 Moved Permanently"); // sets HTTP status code to 301
header("Location: /newpage.html"); // redirect to newpage.html
?>
<?
ob_end_flush
();
?>