By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Properly Redirecting old URLs to Friendly URLs Using PHP

A common problem Webmasters face, is how to 301 permanently redirect their old URLs containing URL parameters, to their SEO friendly versions. This Article goes trough the steps required to do this in PHP, and how to send the correct redirect headers.

Edited: 2013-03-30 12:38

When we change the URL system of our website, its important that we redirect our old URLs to point to the SEO friendly versions, both so that we don't lead visitors into blind alleys, but also so that we don't lose the link juice on links pointing to the old URLs.

What about the old URLs, in the case where you changed the URL system of your website? Many webdesigners, and casual webmasters, simply don't know how to properly redirect these URLs, and some doesn't even understand why its important. Its also important that we send the correct headers, if we want to pass on link juice from links pointing to the old URLs.

This Article expects that you know how to work with PHP and MySQL, if you can't make much sense from the example, you should go and read up on these topics first.

Redirecting URLs using PHP

All we really need to do, is to place a bit of code in the top of our source, before any output is sent to the browser. This code will check if the relevant $_GET variables has been set, and that the identification method is valid, and that it could refer to a entry in our database.

Checking the get variable

The first bit of code. is a single php if check, used to validate the $_GET variable. Lets take the PostID as an example.

if ((isset($_GET['PostID'])) && (preg_match("/^[0-9]+$/D", $_GET['PostID']))) {
  // Stuff to Do!
}

Check if the page exists

Above example checks if the PostID has been set, and that it contains a numeric value. If it dose, then we should check if there exists a entry in our database with the given PostID.

if ((isset($_GET['PostID'])) && (preg_match("/^[0-9]+$/D", $_GET['PostID']))) {
  $SelectThis = mysql_query("SELECT Title FROM Posts WHERE PostID = '{$_GET['PostID']}'", $Connection) or die(mysql_error());
}

Error handling

Friendly URLs are often generated from the Post Title alone, so we only need to select the title field in our MySQL table, and generate the URL to be redirected to from that.

But before we do this, and before we redirect the user to the new URL, we should first check whether the query returned something. And then throw out a 404 error in case didn't. This could be done by using if (!$query), but that would not account for MySQL errors, so we should instead count the rows of the $query, which would allow us to account for real errors. In this case, that would be the $SelectThis variable.

  if (mysql_num_rows($SelectThis) < 1) {
   /* If the number of rows returned was less then one, we return a 404. */

    header('HTTP/1.1 404 Not Found');
    mysql_close($Connection);
    exit();
  }

Above would throw out a standard 404 error, if the post didn't exist in out database.

Generating the friendly URL

The next thing we need to do, is to generate the new friendly URL, so that we can redirect the user to the new URL, if a post was found. That can be done by using str_replace. I.e.

  $Selected = mysql_fetch_assoc($SelectThis);
  $NewUrl = 'http://brugbart.com/OptionalSubdir/'. str_replace(' ', '-', $Selected['Title']) .'.html';

The full example code

The full code required to properly redirect old URLs, is shown below.

if ((isset($_GET['PostID'])) && (preg_match("/^[0-9]+$/D", $_GET['PostID']))) {
  $SelectThis = mysql_query("SELECT Title FROM Posts WHERE PostID = '{$_GET['PostID']}'", $Connection) or die(mysql_error());
  if (mysql_num_rows($SelectThis) < 1) {
   /* If the number of rows returned was less then one,
      or in other words, if the post didn't exist, we return a 404. */

    header('HTTP/1.1 404 Not Found');
    mysql_close($Connection);
    exit();
  }
  $Selected = mysql_fetch_assoc($SelectThis);

  $NewUrl = 'http://brugbart.com/OptionalSubdir/'. str_replace(' ', '-', $Selected['Title']) .'.html';

  Header('HTTP/1.1 301 Moved Permanently'); 
  Header('Location:'. $NewUrl); // The new URL lecation 
  mysql_close($Connection);
  exit();
}