301 Page Redirects using PHP and .htaccess

During the life of a website, its quite common for pages to move around or to ‘re-structure’ your site’s files and folders. However, you can come across issues when people linking to your page go to their ‘stale’ bookmark of your site, and find that page is missing – in fact, they’ll get a ‘404 Page Not Found‘. The same will go for search engines like google and yahoo, and will adversely affect your rankings within their results.

So what do I do?

The most ‘obvious’ thing would be to use a META refresh and redirect the user to the page after say 5 seconds, however, search engines won’t get moved along, and so you’ll only be helping out your visitors. The correct approach is to perform a 301 redirect. A 301 redirect happens before the page is even loaded, thus saving you bandwidth, and redirects the user seamlessly. This can be easily done in PHP like so:

PHP:

  1. header (‘HTTP/1.1 301 Moved Permanently’);

  2. header (‘Location: http://www.domain.com/folder/file.html’);

So for instance, if i’ve moved a page from http://www.olddomain.com/picture.php to http://www.newdomain.com/album.php, you would place the following in picture.php:

PHP:

  1. header (‘HTTP/1.1 301 Moved Permanently’);

  2. header (‘Location: http://www.newdomain.com/album.php’);

This would let browsers AND search engines know about the new page.

I don’t have PHP!

There are some cases where you don’t have PHP, or the file in question can’t be used to execute PHP (e.g. .html .htm). Although there is a way to overcome the latter of these problems by forcing your webserver to parse the .html page as a PHP page, you could alternatively use a .htaccess file if you are running your site on apache. There are two ways to do this, and which option you choose depends on your needs.

If you only need to redirect a few files, then the following placed in your .htaccess would suffice:

redirect 301 /picture.html http://www.newdomain.com/album.php

However, if you wanted to redirect every request to http://www.olddomain.com (including images, javascript soruce files etc) then that is going to be a lot to type out!

The alternative is to apply a redirect using mod_rewrite. This generally comes with apache as standard, and so you should have it at your use. The following would perform a sitewide 301 redirect:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^newdomain.com [NC]
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

The key thing to remember here is the trailing slash in the full domain name.

So there we have it – easy redirects that are search engine friendly, and are also ‘invisible’ to your users.

Taken from jellyandcustard.com