Making Drupal Redirect Missing Pages to Another Site
Redirecting missing files and pages to another site is a common trick when migrating a complex site. However Drupal adds another layer to it. The regular server configurations won't work with Drupal, because it already takes over for any URLs that don't exist on the local filesystem. So if you have a new Drupal site and you want to redirect all missing URLs to an old site, how do you do it? All you need is one extra hook in a custom module:
/**
* Redirects missing pages to old site
*/
function mymodule_init() {
// figure out if this is a valid page by getting the menu_router item for $_GET['q']
$item = menu_get_item();
if ( !$item ) {
// it isn't - go to the old site
$to = $_SERVER['REQUEST_URI'];
header('Location: http://oldsite.com'.$to);
exit();
}
}
This emulates the logic that Drupal uses to decide if it will show "Page not found". By doing this in hook_init we can jump in and take action before it actually returns a 404, by redirecting the visitor to the old site. Both pages and static files that don't exist on the Drupal site will be sent on to the old site. This works because existing static files are served directly by the webserver, so anything that goes to Drupal is either a request for a valid page in the new site (which means it will have a menu_router entry, even if it's just node/%) or an invalid URL that we want to send to the old site. Since menu_get_item caches information there's little duplicated work being done.
This was tested in Drupal 7 but should work in 6 as well.