Setting up a 404 page on your webserver was the easy part. Now you have found that your site or application has begun to exhibit strange behaviors with redirects or variable values or sessions. In this article, I will share my problem and solution so that you don’t waste the hours that I did.

One Line Setup of 404 Page

It doesn’t get any easier than this. You can, of course, name your page anything you want and use a different path. I find it easiest to simply call it /404.php (or whatever language you use) and leave it right at the root, which is also where your .htaccess file will reside.

HTACCESSview code
ErrorDocument 404 /404.php

The Problem

At seemingly random times, I found that my web application would redirect me to my custom 404 page for no reason at all. All pages involved actually existed, but the program was nonetheless sending me to my own error page.

After spending a good hour wondering why some of my SESSION variables were getting setup incorrectly, I decided to go check the Apache logs. The site I was building was on GoDaddy using Deluxe Hosting, and the Apache logs aren’t the easiest to work with. If I had just been looking at Firebug, or other browser debugger, I could have immediately seen the answer.

The Culprit

If you have full control over your Apache logs, check to see if you happen to be inadvertently generating 404 errors with external files, such as shown below. Since you now have a custom 404 page, everything goes there. That means that if you have an unused image in a CSS file that has never been uploaded or a script being called that no longer exists on the server, it will generate a 404 error and actually load your custom 404 page “behind the scenes.”

CSS Images 404 errors


What’s worse is that this all happens after the server-side code (PHP,ASP,Java,etc) has done it’s part and returned data to the screen.
I had some variables that I echoed out and were correct, but were getting changed because the 404 page was loading in the background (after the fact).

How to Fix it

The answer here is obvious. Remove any references to files that don’t exist. Easier said than done, of course. As you can see, it happened to me and I try to be as vigilant as possible.

In my case, I had copied a large chunk of a CSS file from another project to reuse some of the classes, but not all of them. Therefore I ended up with image calls to stuff that didn’t exist, which fired my custom 404 page.

The easiest way to help yourself out and build better web pages is to leave a debugger open at all times (my favorite is Firebug on Firefox when developing) and you will see a red 404 entry pop up for anything on the page that doesn’t exist.