WordPress:Creating an Error 404 Page
While you work hard to make sure that every link actually goes to a specific web page on your site, there is always a chance that a link clicked will slam dunk and become a famous 404 ERROR PAGE NOT FOUND.
All is not lost. If your visitors encounter an error, why not be a helpful WordPress site administrator and present them with a message more useful than "NOT FOUND".
This lesson will teach you how to edit your "error" and "page not found" messages so they are more helpful to your visitors. We'll also show how to ensure your web server displays your helpful custom messages. Finally, we'll go over how to create a custom error page consistent with your Theme's style.
An Ounce of Prevention[ ]
Some errors are avoidable, you should regularly check and double check all your links. Also, if you are deleting a popular but out-of-date post, consider deleting the body of the post, and replacing it with a link referring visitors to the new page.
Understanding Web Error Handling[ ]
Visitors encounter errors at even the best web sites. As site administrator, you may delete out-of-date posts, but another web site may have a link to your inside page for that post.
When a user clicks on a link to a missing page, the web server will send the user an error message such as 404 Not Found. Unless your webmaster has already written custom error messages, the standard message will be in plain text and that leaves the users feeling a bit lost.
Most users are quite capable of hitting the back key, but then you've lost a visitor who may not care to waste their time hunting for the information. So as not to lose that visitor, at the very least, you'll want your custom message to provide a link to your home page.
The friendly way to handle errors is to acknowledge the error and help them find their way. This involves creating a custom Error Page or editing the one that came with your WordPress Theme.
Editing an Error 404 Page[ ]
The default WordPress theme has a 404.php file, but not all Themes have their own custom 404 error template file. If they do, it will be named 404.php. WordPress will automatically use that page if a Page Not Found error occurs.
The normal 404.php page shipped with your Theme will work, but does it say what you want it to say, and does it offer the kind of help you want it to offer? If the answer is no, you will want to customize the message in the template file.
To edit your Theme's 404 error template file:
- Open your WordPress admin panel:
- Choose Design menu. (Presentation pre 2.5)
- Choose the Theme Editor page.
- Check to see if your theme includes a '404 Template' in the list of files.
- Click the link for '404 template' along the right side of the page.
- Edit the message text to say what you want it to say.
- Save your changes. (If the template file is not writable, see Changing File Permissions.)
While you are examining and editing your 404 template file, take a look at the simple structure of the default 404.php file. It basically features tags that display the header, sidebar, and footer, and also an area for your message:
<?php get_header(); ?> <div id="content" class="narrowcolumn"> <h2 class="center">Error 404 - Not Found</h2> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
So, to change the error message your visitor sees, revise the text within the h2 heading and if necessary, add more paragraphs below that.
Creating an Error 404 Page[ ]
If your WordPress Theme does not include a template file named 404.php, you can create your own.
Because every theme is different, there is no guarantee that copying over the 404.php template file found in the WordPress Default Theme will work, but it's a good place to start. The error page you copy from the Default Theme will adopt the style of the current theme because it actually calls the header and footer of the current theme. That's less work for you, and you may only have to edit the message to suit your particular needs.
To use the 404.php template file from the WordPress Default Theme:
- Copy the file /wp-content/themes/default/404.php into the directory of your current theme.
- Then, as described in the previous section, edit the error message to present your desired error message.
If copying the default 404.php into your theme directory does not work well with your theme, you have some other choices:
- Change the Default Theme's 404.php template file's header, sidebar, footer, and other codes to match the rest of the Theme's layout.
Or
- Copy the index.php file of your current theme to a file called 404.php.
- Open that file and delete all sections dealing with posts or comments, see WordPress:The Loop.
- Then, edit your 404 error message.
Advanced 404.php Example[ ]
This is an example of some of the technical capabilities of WordPress 404.php and HTTP Status Code Handling. You should strive to make your 404 error pages as helpful to your site visitors as you can, and when possible you should redirect broken URI's to the correct resource.
The AskApache Google 404 Plugin shows how to handle other types of error status codes that may be handled by your "404.php" template file.
This helps to determine the type of server error so that you can provide the correct http response without wasting bandwidth and CPU for non-404 errors. It tries to issue the correct response using HTTP status codes and the specifications compatible with RFC 2616 specifications.
<?php $ASKAPACHE_S_C = array( '400' => array( 'Bad Request', 'Your browser sent a request that this server could not understand.'), '401' => array( 'Authorization Required', 'This server could not verify that you are authorized to '. 'access the document requested. Either you supplied the '. 'wrong credentials (e.g., bad password), or your browser '. 'doesn\'t understand how to supply the credentials required.'), '402' => array( 'Payment Required', 'INTERROR'), '403' => array( 'Forbidden', 'You don\'t have permission to access THEREQUESTURI on this '. 'server.'), '404' => array( 'Not Found', 'We couldn\'t find <acronym title="THEREQUESTURI">that uri'. '</acronym> on our server, though it\'s most certainly not '. 'your fault.'), '405' => array( 'Method Not Allowed', 'The requested method THEREQMETH is not allowed for the URL '. 'THEREQUESTURI.'), '406' => array( 'Not Acceptable', 'An appropriate representation of the requested resource '. 'THEREQUESTURI could not be found on this server.'), '407' => array( 'Proxy Authentication Required', 'This server could not verify that you are authorized to '. 'access the document requested. Either you supplied the wrong '. 'credentials (e.g., bad password), or your browser doesn\'t '. 'understand how to supply the credentials required.'), '408' => array( 'Request Time-out', 'Server timeout waiting for the HTTP request from the client.'), '409' => array( 'Conflict', 'INTERROR'), '410' => array( 'Gone', 'The requested resourceTHEREQUESTURIis no longer available on '. 'this server and there is no forwarding address. Please remove '. 'all references to this resource.'), '411' => array( 'Length Required', 'A request of the requested method GET requires a valid '. 'Content-length.'), '412' => array( 'Precondition Failed', 'The precondition on the request for the URL THEREQUESTURI '. 'evaluated to false.'), '413' => array( 'Request Entity Too Large', 'The requested resource THEREQUESTURI does not allow request '. 'data with GET requests, or the amount of data provided in the '. 'request exceeds the capacity limit.'), '414' => array( 'Request-URI Too Large', 'The requested URL\'s length exceeds the capacity limit for '. 'this server.'), '415' => array( 'Unsupported Media Type', 'The supplied request data is not in a format acceptable for '. 'processing by this resource.'), '416' => array( 'Requested Range Not Satisfiable', ''), '417' => array( 'Expectation Failed', 'The expectation given in the Expect request-header field could '. 'not be met by this server. The client sent <code>Expect:</code>'), '422' => array( 'Unprocessable Entity', 'The server understands the media type of the request entity, but '. 'was unable to process the contained instructions.'), '423' => array( 'Locked', 'The requested resource is currently locked. The lock must be released '. 'or proper identification given before the method can be applied.'), '424' => array( 'Failed Dependency', 'The method could not be performed on the resource because the requested '. 'action depended on another action and that other action failed.'), '425' => array( 'No code', 'INTERROR'), '426' => array( 'Upgrade Required', 'The requested resource can only be retrieved using SSL. The server is '. 'willing to upgrade the current connection to SSL, but your client '. 'doesn\'t support it. Either upgrade your client, or try requesting '. 'the page using https://'), '500' => array( 'Internal Server Error', 'INTERROR'), '501' => array( 'Method Not Implemented', 'GET to THEREQUESTURI not supported.'), '502' => array( 'Bad Gateway', 'The proxy server received an invalid response from an upstream server.'), '503' => array( 'Service Temporarily Unavailable', 'The server is temporarily unable to service your request due to '. 'maintenance downtime or capacity problems. Please try again later.'), '504' => array( 'Gateway Time-out', 'The proxy server did not receive a timely response from the '. 'upstream server.'), '505' => array( 'HTTP Version Not Supported', 'INTERROR'), '506' => array( 'Variant Also Negotiates', 'A variant for the requested resource <code>THEREQUESTURI</code> '. 'is itself a negotiable resource. This indicates a configuration error.'), '507' => array( 'Insufficient Storage', 'The method could not be performed on the resource because the '. 'server is unable to store the representation needed to successfully '. 'complete the request. There is insufficient free space left in your '. 'storage allocation.'), '510' => array( 'Not Extended', 'A mandatory extension policy in the request is not accepted by the '. 'server for this resource.') ); // prints out the html for the error, taking the status code as input function aa_print_html ($AA_C){ global $AA_REQUEST_METHOD, $AA_REASON_PHRASE, $AA_MESSAGE; if($AA_C == '400'||$AA_C == '403'||$AA_C == '405'||$AA_C[0] == '5'){ @header("Connection: close",1); if($AA_C=='405')@header('Allow: GET,HEAD,POST,OPTIONS,TRACE'); echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>"; echo "<title>$AA_C $AA_REASON_PHRASE</title>"; echo "<h1>$AA_REASON_PHRASE</h1>\n<p>$AA_MESSAGE<br>\n</p>\n</body></html>"; return true; } else return false; } // Tries to determine the error status code encountered by the server if(!isset($_REQUEST['error'])) $AA_STATUS_CODE = '404'; else $AA_STATUS_CODE = $_REQUEST['error']; if(isset($_SERVER['REDIRECT_STATUS']) && $_SERVER['REDIRECT_STATUS']!='200') $AA_STATUS_CODE = $_SERVER['REDIRECT_STATUS']; $AA_REQUEST_METHOD = $_SERVER['REQUEST_METHOD']; $AA_THE_REQUEST = htmlentities(strip_tags($_SERVER['REQUEST_URI'])); $AA_REASON_PHRASE = $ASKAPACHE_S_C[$AA_STATUS_CODE][0]; $AA_M_SR=array(array('INTERROR','THEREQUESTURI','THEREQMETH'), array('The server encountered an internal error or misconfiguration '. 'and was unable to complete your request.',$AA_THE_REQUEST,$AA_REQUEST_METHOD)); $AA_MESSAGE=str_replace($AA_M_SR[0],$AA_M_SR[1],$ASKAPACHE_S_C[$AA_STATUS_CODE][1]); // begin the output buffer to send headers and resonse ob_start(); @header("HTTP/1.1 $AA_STATUS_CODE $AA_REASON_PHRASE",1); @header("Status: $AA_STATUS_CODE $AA_REASON_PHRASE",1); if(!aa_print_html($AA_STATUS_CODE)){ ?> <?php get_header();?> <div id="content"> <div class="post"> <h1><?php _e("$AA_STATUS_CODE $AA_REASON_PHRASE"); ?></h1> <?php if(function_exists('aa_google_404')) aa_google_404(); ?> </div> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> <?php } exit; exit(); ?>
Tips for Error Pages[ ]
There are various improvements you can make to your 404 Error web pages so let's look at some of your options.
Sending Proper Headers[ ]
By default, WordPress continues to send 404 pages as if they were fine. To make search engines like Google spider these pages correctly, you can add this line to the top of your theme's 404.php file.
<?php header("HTTP/1.1 404 Not Found"); ?> <?php header("Status: 404 Not Found"); ?>
You may have to add this before the above code in some cases.
<?php ob_start(); ?>
Writing Friendly Messages[ ]
When an error message is displayed, you can say many things to help a visitor feel reassured they've only encountered a minor glitch, and you're doing the best you can to help them find the information they want. You can say something clever like:
"Oops, I screwed up and you discovered my fatal flaw. Well, we're not all perfect, but we try. Can you try this again or maybe visit our <a title="Our Site" href="http://example.com/index.php">Home Page</a> to start fresh. We'll do better next time."
You should also attempt to show the user what they want. Check out the AskApache Google 404 Plugin to add google search results to your 404.php
Or, say something shorter and sweeter. Almost anything you say is better than 404 Error Page Not Found. You can find more information about writing 404 Error pages on the Internet, like List Apart's Perfect 404.
As an implementation of the Perfect 404 page, this solution will tell the user it's not their fault, if it isn't and email the webmaster, according to WordPress's database. Helpful 404 page
When a visitor gets a 404 error page, it can be intimidating, and unhelpful. Using Wordpress, you can take the edge off a 404 and make it helpful to users, and yourself, too, by emailing whenever the user clicks a link to a non-existent page. If you use this, don't forget o
<p>You <?php #some variables for the script to use #if you have some reason to change these, do. but wordpress can handle it $adminemail = get_bloginfo('admin_email'); #the administrator email address, according to wordpress $website = get_bloginfo('url'); #gets your blog's url from wordpress $websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress if (!isset($_SERVER['HTTP_REFERER'])) { #politely blames the user for all the problems they caused echo "tried going to "; #starts assembling an output paragraph $casemessage = "All is not lost!"; } elseif (isset($_SERVER['HTTP_REFERER'])) { #this will help the user find what they want, and email me of a bad link echo "clicked a link to"; #now the message says You clicked a link to... #setup a message to be sent to me $failuremess = "A user tried to go to $website" .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. "; $failuremess .= "It wasn't their fault, so try fixing it. They came from ".$_SERVER['HTTP_REFERER']; mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'], $failuremess, "From: $websitename <noreply@$website>"); #email you about problem $casemessage = "An administrator has been emailed about this problem, too.";#set a friendly message } echo " ".$website.$_SERVER['REQUEST_URI']; ?> and it doesn't exist. <?php echo $casemessage; ?> You can click back and try again or search for what you're looking for: <?php include(TEMPLATEPATH . "/searchform.php"); ?> </p>
Add Useful Links[ ]
If you encounter a "page not found" situation on the WordPress site, it is filled with helpful links to direct you to the various categories and areas of information within the WordPress site. Check it out at http://wordpress.org/brokenlink.php.
To add similar useful links to your 404 page, create a list, or a paragraph, so the visitor can easily determine which section might be useful to visit. Information of that nature is much better than having the user just reach a dead-end. To help you understand how to link to documents within your site, especially to WordPress:Pages and Categories, see WordPress:Linking_Posts_Pages_and_Categories.
Testing 404 Error Messages[ ]
To test your custom 404 page and message, just type an URL address into your browser for your website that doesn't exist. Make one up or use something like:
http://example.com/fred.php
This is sure to result in an error unless you actually have a php file called fred. If your error page doesn't look "right", you can go back and edit it so it works correctly and matches your Theme's look and feel.
Help Your Server Find the 404 Page[ ]
By default, if WordPress cannot find a particular page it will look for the 404.php web page. However, there may be cases where the web server encounters a problem before WordPress is aware of it. In that case, you can still guarantee that your web server sends the visitor to your 404.php template file by configuring your web server for custom 404 error handling.
To tell your web server to use your custom error files, you'll need to edit the .htaccess file in the main directory (where main index.php file resides) of your WordPress installation. If you don't have an .htaccess file, see Editing Rewrite Rules (.htaccess) on how to create an .htaccess file.
To ensure the server finds your 404 page, add the following line to your .htaccess
file:
ErrorDocument 404 /index.php?error=404
The url /index.php is root-relative, which means that the forward slash begins with the root folder of your site. If WordPress is in a subfolder or subdirectory of your site's root folder named 'wordpress', the line you add to your .htaccess file might be:
ErrorDocument 404 /wordpress/index.php?error=404
Additional Error Code Handling[ ]
- Mental Excercise for the most part you don't need this*
Please try to use as many static errordocuments as you can, as a single /missing.html file being server for a missing image (404 Not Found) would take up incredibly less CPU and Memory than having it processed by /index.php?error=404
To enable your WordPress 404.php template file to handle additional server errors, you can use something like this in your .htaccess file.
Notice how some errors are handled by WordPress, while other errors output a static .html document, and a few are actual php scripts. For instance, a 500 error would not be suitable to be handled by WordPress, as the 500 error could be occuring due to WordPress, like a bad plugin. So by instructing your server to instead serve a static .html document you can display a much more helpful error message to your visitors.
ErrorDocument 400 /cgi-bin/error-deal.php ErrorDocument 402 /cgi-bin/error-deal.php ErrorDocument 403 /error/403/index.html ErrorDocument 404 /index.php?error=404 ErrorDocument 405 /error/405/index.php ErrorDocument 406 /index.php?error=406 ErrorDocument 407 /index.php?error=407 ErrorDocument 408 /index.php?error=408 ErrorDocument 409 /index.php?error=409 ErrorDocument 410 /index.php?error=410 ErrorDocument 411 /index.php?error=411 ErrorDocument 412 /index.php?error=412 ErrorDocument 413 /index.php?error=413 ErrorDocument 414 /index.php?error=414 ErrorDocument 415 /index.php?error=415 ErrorDocument 416 /index.php?error=416 ErrorDocument 417 /index.php?error=417 ErrorDocument 418 /index.php?error=418 ErrorDocument 419 /index.php?error=419 ErrorDocument 420 /index.php?error=420 ErrorDocument 421 /index.php?error=421 ErrorDocument 422 /index.php?error=422 ErrorDocument 423 /index.php?error=423 ErrorDocument 424 /index.php?error=424 ErrorDocument 425 /index.php?error=425 ErrorDocument 426 /index.php?error=426 ErrorDocument 500 /error/503/index.html ErrorDocument 501 /index.php?error=501 ErrorDocument 502 /index.php?error=502 ErrorDocument 500 /error/503/index.html ErrorDocument 504 /index.php?error=504 ErrorDocument 505 /index.php?error=505 ErrorDocument 506 /index.php?error=506 ErrorDocument 507 /index.php?error=507 ErrorDocument 508 /index.php?error=508 ErrorDocument 509 /index.php?error=509 ErrorDocument 510 /index.php?error=510
Questions About Error Files[ ]
- Why not just hard code the path all the way to the 404.php file?
- By allowing index.php to call the error file, you ensure that the 404.php file used will change automatically as you change your theme.
- What happens if I switch to a theme that does not have a 404.php file?
- Visitors clicking on a broken link will just see a copy of the home page of your WordPress site (index.php), but the URL they see will be the URL of the broken link. That can confuse them, especially since there is no acknowledgement of the error. But this is still better than a getting a "NOT FOUND" message without any links or information that could help them find what they seek.
Other Error Numbers[ ]
Here are more standard web error numbers. You can see the headers and output at Apache Status Codes and ErrorDocuments
- 100 Continue
- 101 Switching Protocols
- 102 Processing
- 200 OK
- 201 Created
- 202 Accepted
- 203 Non-Authoritative Information
- 204 No Content
- 205 Reset Content
- 206 Partial Content
- 207 Multi-Status
- 300 Multiple Choices
- 301 Moved Permanently
- 302 Found
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 307 Temporary Redirect
- 400 Bad Request
- 401 Authorization Required
- 402 Payment Required
- 403 Forbidden
- 404 Not Found
- 405 Method Not Allowed
- 406 Not Acceptable
- 407 Proxy Authentication Required
- 408 Request Time-out
- 409 Conflict
- 410 Gone
- 411 Length Required
- 412 Precondition Failed
- 413 Request Entity Too Large
- 414 Request-URI Too Large
- 415 Unsupported Media Type
- 416 Requested Range Not Satisfiable
- 417 Expectation Failed
- 422 Unprocessable Entity
- 423 Locked
- 424 Failed Dependency
- 425 No code
- 426 Upgrade Required
- 500 Internal Server Error
- 501 Method Not Implemented
- 502 Bad Gateway
- 503 Service Temporarily Unavailable
- 504 Gateway Time-out
- 505 HTTP Version Not Supported
- 506 Variant Also Negotiates
- 507 Insufficient Storage
- 510 Not Extended
Authorization errors are handled by the WordPress program.