making bbPress (and WordPress) work better!

Better 404 error page behavior for WordPress

After wasting an hour trying to debug a problem I was having with WordPress I discovered I had actually fixed it within the first minute – it was just that my browser was obeying the caching behavior set by WordPress for the 404 page! After a hard-refresh I found that the error was gone and it was working properly.

So I desided to improve the WordPress 404 behavior.
You can do it too, add this to the very top of your header.php template

if (is_404()) {
header("HTTP/1.1 404 Not Found");
header ("Pragma: no-cache"); // HTTP 1.0
header ("Expires: Mon, 25 Jul 1995 05:00:00 GMT"); // Date in the past
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header ("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP 1.1
header ("Cache-Control: post-check=0, pre-check=0", false); // HTTP 1.1
// echo "\n<!--\n"; print_r($_REQUEST); echo "\n-->\n";

That will force it not to cache via various known techniques to defeat most browsers.

The last line commented out with the echo is to help diagnose any problems you may have with rewrites or other variables not getting passed properly through WordPress. If you uncomment it, you’ll see some helpful info when you view the source of the 404 error page.

3 responses

  1. This can also go at the top of 404.php, can it not?

    August 11, 2006 at 1:34 am

  2. Yes, depending how your 404.php template is setup.

    The headers have to be sent before any other info is sent, so it has to be before get_header(); is called.

    If you’re setup like the default template then yes.

    August 11, 2006 at 10:15 am

  3. Floroskop

    I think this try.

    March 19, 2008 at 3:07 am

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s