WordPress Quick 404 Redirect Page

11 Feb 2011

I’m not a competent PHP programmer but I’ve recently moved my website to a framework based on WordPress, with a custom theme designed by Alex Rozanski so I’ve had to learn the basics.

Part of this migration was moving from my old custom PHP/HTML/CSS website to a new WordPress based structure and this meant working out what to do with files that had moved. Like most WordPress based site mine has a custom “404” page which is used when an unrecognised URL is requested. The problem I had was that links to PDF files for my papers and articles are scattered all over the place embedded in sites like Google, DBLB and Citeseer. All of those files have moved to a new location and displaying a generic error page isn’t that helpful, so the question was how to redirect those requests to the right files?

There are lots of ways to solve this problem in WordPress and PHP, plugins (like Redirection), Apache aliases and custom “404” pages. In my case, I wanted something simple (which I didn’t need to change once it was done), which didn’t involve messing with the Apache configuration, which was also simple to implement. After quite a lot of Google searches I concluded that there wasn’t a simple solution out there already, so I decided to create something myself.

After some research, the solution proved to be quite simple. The basic code is shown below.

/* Custom WordPress 404.php file */
    /* Map of old file locations to new ones */
    $movedFileMap = array (
        "old-download-file1.pdf" => "path/to/new-download-file1.pdf",
        "old-download-file2.pdf" => "path/to/new-download-file2.pdf",
        /* ... */
    $fileName=end(explode('/', $_SERVER['REQUEST_URI']));
    $mappedName = $movedFileMap[$fileName] ;
    if ($mappedName != "") {
        $mappedPath = "/media/{$mappedName}" ;
       <h1>File Not Found</h1>
        <p>Your request for <?php echo($fileName);?> has moved to here:
            <?php echo($mappedPath);?>.</p>
        <!-- HTML here to display useful text when the mapping fails -->

The implementation probably falls into the “simplest thing possible” category and it is just a PHP array (which is a map in other languages) from the old filename to the new filename. If a URI’s final element is found in the map, a helpful message is displayed to redirect the user to the new file location.

The only clever bit is on line 10 where the incoming URL is split up using explode() and the last element pulled out using end() to work out which file is being requested, so that it can be looked up in the $mappedFile map.

Finally, if the URL’s final element isn’t found then a more general help message (with links to content on the site or a search box) should be displayed.

Hopefully this will help some other people moving their websites to WordPress!

published under Technology