How to Bulk 301 Redirect in PHP

I usually do my redirects with an .htaccess file, but it is also possible to do redirects with PHP. A quick example is shown below:

<?php
// Create a function to send the correct headers
function redirect($url) {
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: $url");
   exit();
}

// Get the path to the file that was requested
$filename = $_SERVER['REQUEST_URI'];

// Perform the redirects
switch ($filename) {
case "/old-page1.html":
   redirect("http://www.example.com/new-page1");
   break;
case "/old-page2.html":
   redirect("http://www.example.com/new-page2");
   break;
case "/old-page3.html":
   redirect("http://www.example.com/new-page3");
   break;
}
?>

One reason you might do this is if the .htaccess redirects are not working and you need immediate results.

Tips for success:

  1. Make sure that there is no whitespace or content before the opening PHP tag, and that nothing is sent to the browser before the headers.
  2. Check your redirects with the Firefox liveHTTPheaders extension to make sure the correct headers are being sent.

Update: 301 OK Error

[Update, December 26, 2006]

I added a 301 redirect to a site with PHP today and get an error when I checked the headers. The page redirected, but was sending a header that said "301 OK" instead of the correct "301 Moved Permanently". Search engines may not obey an incorrectly sent header.

The code below redirects the /index.php page to the correct home page URL, which is http://www.example.com/. In this case, Google had indexed both URLs and I needed to redirect everything to a single home page URL. See Google engineer Matt Cutts' post on URL canonicalization for more information on the reasons for this kind of redirect.

Here is the original code, that was sending incorrect headers:

$homepage = 'http://www.example.com/';
$filename = $_SERVER['REQUEST_URI'];
if ($filename == '/index.php') {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $homepage");
}

Here is the fixed code that sent the correct headers:

$homepage = 'http://www.example.com/';
$filename = $_SERVER['REQUEST_URI'];
if ($filename == '/index.php') {
    header("Status: 301 Moved Permanently");
    header("Location: $homepage");
}

See my post about PHP/Drupal 404 OK errors for more information.

Syndicate content