Daily Archives: January 14, 2014

Archiving An Old Web Site To A Subdomain with .htaccess and PHP

I was recently browsing a website that had been upgraded. For the sake of argument, let’s say the original site was hosted at:


The new site content was placed at the above address, and the previous content moved to:


The problem that is now faced is that there are many links out there to pages on www.awesomesite.com that no longer exist there, and do exist on www.old.awesomesite.com. The URLs need to be redirected, but not all of them, because the new content on www.awesomesite.com needs to be unaffected.

How can we fix this?

Well, most questions online about mod_rewrite and .htaccess files that deal with subdomains are looking to redirect a whole site, or 404 redirects to a static page, which isn’t what we want.

Here is one way to fix it.

1. .htaccess file to redirect to a PHP script
Add an .htaccess file in the root level directory of the webserver (or add this line to an existing one in the right place) with this content:

ErrorDocument 404 /404.php

This will run a PHP script called 404.php every time the web server is asked for a page it can’t find.

2. 404.php – look for the file somewhere else.
The next step is to run this script that will check to see what file you just tried to access at www.awesomesite.com (OK, now we’ll switch to www.kje.ca), and look for it at www.old.kje.ca. If it exists, you’ll get forwarded there without seeing anything. If it doesn’t exist, then you’ll be left a pleasant message.

$test = 'http://www.old.kje.ca' . $_SERVER['REQUEST_URI'];
$file_headers = @get_headers($test);
if($file_headers[0] != 'HTTP/1.1 200 OK') {
   $exists = false;
else {
   $exists = true;
   header("Location: $test");

You were looking for <?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>

<p> Tried to load <?php echo $test ?> but we couldn't find that.

3. Try It Out

So now, a test.

The file one.html doesn’t exist on http://www.kje.ca, but does exist on http://www.old.kje.ca. But, if you click on either link:



You get to the same page at


Now, if you try the link below, that doesn’t exist on either site, you’ll get an error message:


I hope this helps!