Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment ⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig
Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label Errors. Show all posts
Showing posts with label Errors. Show all posts

Monday, September 1, 2014

A lot of funny 404 pages have been shared recently: carefully crafted memes, funny GIFs, even the odd interactive game. But if the 404 doesn’t help your visitors, then what’s the point?
A visitor could find themselves on a 404 page for one of many reasons: a mistyped address, a bad link from somewhere else, a deleted page or content that has moved elsewhere. While you can prevent errors from moved pages with redirects, you can’t control people’s mistakes.

Being Helpful

People who land on your website are looking for its content, usually via a link. They would have clicked that link expecting one thing, so why show them a hand-drawn panda? Instead, your 404 page should get them to where they need to be.
This problem isn’t new, and we’ve seen a lot of ideas on how to handle it. Showing a search form or linking to the home page is reasonable. Yet those are passive solutions that don’t solve the visitor’s problem. A more direct approach would be to guess where the visitor intended to go and suggest that page.

Suggesting The Right Page

One way to suggest the right page is to search for it yourself and present the result. Luckily, we don’t have to write a search engine to do this (although, if you have one handy, good for you!). Instead, we can use Google’s Custom Search API.
Google’s Custom Search API is a tool for searching within an individual website. When set up, it enables you to retrieve what it considers to be the best match from your website. It does need a search phrase, though. So, to give Google something to search with, we’ll use the path of the URL that the user is currently on.

Caveat: Limits Abound

Before jumping into the “how to” part, it’s worth noting that the free tier for this API has a limit of 100 calls per day. You might want to go light on the testing while working on it. I managed to burn through the 100 calls in less than an hour, and I had to wire part of it together without seeing the result till the next day.
While someone with a small website might be fine with this limit, paid upgrades are available. Google’s API documentation mentions a price of $5 per 1000 queries and up to 10,000 queries per day.

Setting Up

Before using the Custom Search API, we need to let Google know who we are and get some access keys.

Search Engine ID

We need to go through a few steps before we can fly through those 100 API requests. First, register your site-specific search engine.
  • Select “Add.”
  • Input your website’s URL (yoursite.com) in “Sites to search.”
  • Hit “Create.”
You now need to find your “Search engine ID.” Click “Edit” on the search engine that you created, then the “Search engine ID” button. Take note of that code!

Developer API Access

Next, go to the Developers Console.
If you don’t yet have a project, select the “New Project” option and fill in the form.
Under “APIs,” activate the “Custom Search API” by switching the “Off” button to “On.” Then, select “Credentials,” then “Create New Key,” and choose the “Browser Key” option. Take note of the API key!

JavaScript

Armed with both a search engine ID and an API key, you can now start hitting the API. The code below requires jQuery. It does some AJAX JSON stuff, so I’d rather lean on the framework to ensure that it works across browsers.
Before creating functions, we should consider the environment that our code will run in. Because we’re writing JavaScript on the front end, our code might run alongside other plugins and scripts. So, let’s build a little space to cleanly separate our functions from everything else:
function createCustomSearch() {
// Private variables and methods here
}
Within our customSearch object, we can define methods and variables safely away from the global context. First, let’s set up some variables to use later:
function createCustomSearch() {
  // Some private variables for this object
  var context = this;
  var dialog = document.querySelector('dialog');
  // Your keys
  var engineID = 'YOUR_ENGINE_ID';
  var apiKey = 'YOUR_API_KEY';
}
Replace the keys with those we generated earlier.
Initially, we establish a local context by storing this in a variable. We’ll use this to access a showDialog method later.

Trying A Search

First, we’ll add a method that tries a custom search:
function customSearchConstructor() {
  // Some private variables for this object
  var context = this;
  var dialog = document.querySelector('dialog');
  // Your keys
  var engineID = 'YOUR_ENGINE_ID';
  var apiKey = 'YOUR_API_KEY';
  this.trySearch = function(phrase) {
    var queryParams = {
      cx: engineID,
      key: apiKey,
      num: 10,
      q: phrase,
      alt: 'JSON'
    }
    var API_URL = 'https://www.googleapis.com/customsearch/v1?';
    // Send the request to the custom search API
    $.getJSON(API_URL, queryParams, function(response) {
      if (response.items && response.items.length) {
        console.log(response.items[0].link);
      }
    });
  };
}
This trySearch method takes a phrase and sends it along with your keys as a request to Google’s API. The response is then checked, and the first link that it finds will be logged to the console. You would call it like so:
var customSearch = new customSearchConstructor();
customSearch.trySearch('cat');
Assuming that your website contains pages about cats (and whose doesn’t?), you should see something logged in your console.

Getting The Search Phrase

Next, we’ll write some code to get the path from the URL of the page. This path will become the search phrase.
$(document).ready(function() {
  var customSearch = new customSearchConstructor();
  var path = window.location.pathname;
  var phrase = decodeURIComponent(path.replace(/\/+/g, ' ').trim());
  customSearch.trySearch(phrase);
});
Within the jQuery ready method, we’ll pick up the pathname part of the current URL and create a search phrase from it. We’ll decode the URI, replace any forward slashes with spaces, and send the result to the trySearch method.

Replacing Strings With JavaScript

One handy thing to know is how to replace a global regular expression in JavaScript. This one is a set of matches separated by pipes:
/\/+/g
The first and last forward slashes (/) are there to contain the expression. Within it, we escape a backslash character (\/) so that it is treated as an actual character. The + will match any instances of multiple slashes, and the g then tells it to replace every instance in the string.

Showing The Redirect

In my first version, I had the page redirect immediately. That was fun but not a great experience for the visitor. The page would load, flicker and jump elsewhere.
An alternative approach is to present the option as an overlay and as a link that the visitor can click. This way, the visitor better understands what has happened and sees a clear way to proceed. And they will have the option not to proceed if the result doesn’t suit them.

Other Approaches

Showing a single result is one way to go about this, but it would be worth considering more than the first result. If you wish to give the visitor more options, then your 404 page could show all of the returned pages as a set. Depending on the quality of the results from the custom search, this might be better.
For this example, let’s assume that the first result returned is always the most relevant, and we’ll present a single option in the form of a dialog overlay.
Also, consider cases in which no results are returned. Ensure that your 404 page contains some helpful message or content.

Starting A Dialog

If we find a result, let’s show it as a modal that prompts the user. To help with this, we’ll be able to use the new dialog element in the near future. Originally intended for dialogue from movies, the element is back and can now show any content that needs to be popped up in front of other content. In other words, we now have a native HTML5 modal element.
Let’s define the dialog in HTML:
<dialog>
  <h2>
    Hey, is this what you meant?
    <span class="suggestion"></span>
    <span class="nope">No thanks</span>
  </h2>
</dialog>

Polyfill For Older Browsers

Before calling the JavaScript that will show and hide this dialog, we need to consider older browsers. The dialog element is very new and so isn’t supported everywhere. To fix this, we can use the helpful polyfill provided by Google.
This polyfill requires a little JavaScript. The following external script will need to be called before we create the dialog:
<script src="https://cdn.rawgit.com/GoogleChrome/dialog-polyfill/master/dialog-
polyfill.js"></script>
This script includes a registerDialog method that wraps the dialog selector with a few handy functions that reproduce the native API. We can use it in our customSearch object:
function createCustomSearch() {
  …
  var dialog = document.querySelector('dialog');
  // Apply the polyfill
  dialogPolyfill.registerDialog(dialog);
  …
}

Showing And Hiding

We now have a dialog element, with extra methods added by the registerDialog polyfill. Let’s add some methods to show and hide the element:
function createCustomSearch() {
  …
  this.showDialog = function (url) {
    var suggestedLink = $('<a></a>');
    // Verify that the suggested URL is from this domain
    var hostname = new RegExp(location.host);
    if (hostname.test(url)) {
      suggestedLink.attr('href', url);
      suggestedLink.text(url);
      $('dialog .suggestion').html(suggestedLink);
      dialog.showModal();
    }
  };
  this.hideDialog = function () {
    dialog.close();
  };
}
We’ve got two methods here. The first, showDialog, takes a URL, places it in the dialog element, and calls the showModal method provided by the polyfill.
To protect ourselves, we’re verifying the URL. Because we’re expecting this script to return another page from the same website, we verify that the returned URL’s host name and the local website’s host name are the same.
The URL is then used to generate an anchor, which we place in the dialog HTML.
The second method, hideDialog, hides the modal using its own close method.

Styling The Dialog

Lastly, let’s add some style. The default modal style is a bit too boxy. We’ll make it subtler and give it a dark background with some CSS:
dialog {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  text-align: center;
  color: #fff;
  border: none;
  background: none;
}

dialog[open] {
  display: block;
}

dialog[open]:before {
  position: fixed;
  z-index: -1;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  content: '';
  background: rgba(0,0,0,.8);
}

dialog span {
  display: block;
}

dialog span.suggestion {
  font-size: 1.75em;
  line-height: 2.5em;
}

dialog h2 {
  line-height: 1.5em;
  padding-top: 2em;
}

dialog a {
  padding: .25em;
  border-radius: .25em;
  background: rgba(200,200,255,.9);
}

dialog .nope {
  font-size: .75em;
  cursor: pointer;
  color: #aaa;
}
We’re referring directly to the dialog in this CSS. For more flexibility, you might prefer to refer to it by a class.
Tweak the various styles to fit your design. The main goal of this CSS is to define how the dialog looks, and have it display: block when given the class of open. The other styles, from position to color, are entirely up to you.

Wiring In The Search

Next, we need to adjust that trySearch method from earlier to use the dialog. We do this by placing the showDialog method call within the JSON response callback. Here’s the full script:
function customSearchConstructor() {
  // Some private variables for this object
  var context = this; // Keeps the parent context available so that we can call local methods
  var dialog = document.querySelector('dialog');
  // Apply the polyfill
  dialogPolyfill.registerDialog(dialog);
  // Your keys
  var engineID = 'YOUR_ENGINE_ID';
  var apiKey = 'YOUR_API_KEY';
  this.trySearch = function(phrase) {
    var queryParams = {
      cx: engineID,
      key: apiKey,
      num: 10,
      q: phrase,
      alt: 'JSON'
    }
    var API_URL = 'https://www.googleapis.com/customsearch/v1?';
    // Send the request to the custom search API
    $.getJSON(API_URL, queryParams, function(response) {
      if (response.items && response.items.length) {
        context.showDialog(response.items[0].link);
      }
    });
  };
  this.showDialog = function (url) {
    var suggestedLink = $('<a></a>');
    // Verify that the suggested URL is from this domain
    var hostname = new RegExp(location.host);
    if (hostname.test(url)) {
      suggestedLink.attr('href', url);
      suggestedLink.text(url);
      $('dialog .suggestion').html(suggestedLink);
      dialog.showModal();
    }
  };
  this.hideDialog = function () {
    dialog.close();
  };
}
$(document).ready(function() {
  var customSearch = new customSearchConstructor();
  var path = window.location.pathname;
  var phrase = decodeURIComponent(path.replace(/\/+/g, ' ').trim());
  customSearch.trySearch(phrase);
  $('dialog .nope').click(function() {
    customSearch.hideDialog();
  });
});

Fallbacks And Other Strategies

API limits aside, it’s possible that a match isn’t found for the mistyped URL. In this case, showing the visitor some helpful content would be a good idea. Depending on your website, you could show recent articles or recently updated pages or perhaps even a custom search box.
Google’s Custom Search Engine gives us the option to get some embedding code. Select your existing engine and then the “Get code” button to find this. Whatever content you decide to show as a fallback, it will be better for your visitors than showing a funny picture. It might not be as much fun, but it will help visitors find what they need.
I hope you’ve enjoyed this article. If you want to share it, please double-check that the URL is correct. Or don’t. I’m sure it’ll be fine.

Saturday, December 3, 2011

A Guide To PHP Error Messages For Designers

PHP is widely available with inexpensive hosting plans, which makes it a popular choice for developers who write software for the Web. From big platforms, such as WordPress, down to small scripts, such as ones to display image galleries or to send forms to email, thousands of script and products are out there written in PHP that can be installed and used even if you don’t know much about PHP yourself.
I have been a PHP developer for 10 years, and my company has developed a content management system, written in PHP, that is intended to be very simple to install and get started with. So, I spend a lot of time working with designers who are installing a PHP script for the first time. If you are installing a script and something goes wrong, PHP can be incredibly infuriating. Until you know what they mean, PHP errors can be baffling. My favorite message is:
1Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
Paamayim Nekudotayim means “double colon” in Hebrew! But double colon is a lot easier to debug than T_PAAMAYIM_NEKUDOTAYIM.
This article is aimed at designers who are not PHP developers but need to install PHP scripts from time to time. Thus, the problems and error messages we will look at here are those you are most likely to encounter when installing scripts, rather than when writing PHP. The tips should help you work through other error messages and should at least help you give clear information to the script’s developer if you need to ask them for assistance.

“All I Get Is A Blank Page!”

Before we can diagnose PHP errors, we need to see some PHP errors. Ideally, you would first be installing the script locally, perhaps using MAMP on a Mac or XAMPP, both of which allow you to turn on error messages easily. You can get PHP to just spit the errors out directly on the screen or log them to a file for viewing.
If, however, you are installing a script directly in your hosting account, the host will likely have disabled the display of all PHP error messages. This is sensible for security, because an error message could give away important information about the server or database, but it isn’t so useful if you are trying to configure a script. If error displays have been turned off, then a fatal error before any output is made to the page would result in a blank page. An error that happens after some HTML has been outputted would result in the markup being “cut off” (stopping at the point where the error occurred). If you “View source” and see a completely blank page or half a page or are getting a “500 internal server error,” then a PHP error is probably the culprit.

Locate the Error Log

On a live server, you should have access to the PHP error log. This is different than the Web server error log, which shows things such as 404 errors when a page or image is not found. The PHP log gives information on errors and warnings in PHP itself. The host should have configured PHP to send errors to a log rather than write them to the screen.
If no error log can be found, then you might be able to configure PHP to maintain one in a location that you specify. To do this, create a directory on your website named errors. Make this directory writable. Then add the code below to the .htaccess file at the root of your website. If you do not have an .htaccess file, create one.
1php_flag  log_errors on
2php_flag display_errors off
3php_value error_log  /your/path/public_html/errors/php_error.log
Then, protect the errors directory so that the file cannot be downloaded from the Web. You might be able to do this in the control panel or just by creating a new .htaccess file, this time in the errors directory.
1Order allow,deny
2Deny from all
If you now run the script that caused the error, the error message should get added to the php_error.log file. If it doesn’t work, try creating the file yourself first in the errors directory and making it writable.
If you have no luck creating an error log, then open a support ticket with your hosting provider, explaining what you are trying to achieve and inquiring how to do it.

Errors, Notices And Warnings

PHP classifies the messages that go to the error log as either errors, notices or warnings. These have different levels of severity. An error is something broken in your code. It needs fixing and will cause PHP to stop executing.
A warning is essentially PHP saying, “What you’re doing will likely cause a problem, but I’ll try to continue.”
A notice alerts you to something that needs attention in your script. It could be that the version of PHP on your server is newer than the one supported by the script. Things in PHP are deprecated in the same way that elements in the HTML specification get deprecated. When something is deprecated, it means that it will be removed in the future, so the notice lets you know this.
Errors in a purchased or open-source script are most likely an issue with your installation, assuming that your version of PHP meets the requirement. If a script is throwing out warnings that you cannot fix, then you should probably raise them with technical support. You can usually ignore notices, although you should check that the latest version of the script is installed. If a lot of notices are being thrown out, it could indicate a poor-quality script.
If the trick above for turning on error logging worked for you, you can set the level of error reporting in the .htaccess file, too:
1php_flag  log_errors on
2php_flag display_errors off
3php_value error_log  /your/path/public_html/errors/php_error.log
4php_value error_reporting 1
The above will add only errors to the error_log.
1php_flag  log_errors on
2php_flag display_errors off
3php_value error_log  /your/path/public_html/errors/php_error.log
4php_value error_reporting -1
Setting error_reporting to -1 will log all errors, warnings and notices. If you do this, then you’ll definitely want to set php_flag display_errors to off, so that notices do not get outputted to your website’s pages.
screenshot

The First Error Is The Important One

If you are displaying errors to the page and hit a PHP error, you could run into a terrifying page full of errors. If you are reviewing errors in a log, refresh the page that is generating the error and then check the log. You might find a long set of errors for the same page; they should all have the same time code, helping you to identify them as a set. This usually happens when the first error is a warning; the script tries to continue running but hits more problems related to the initial warning. Fix the initial warning, and you might find that all of the other issues go away.

Database-Related Errors

Many of the errors people encounter when installing a script have to do with the connection to the database. Usually, when a script needs to make a database connection, you will be asked for four bits of information: the database’s user name and password, the server’s address (which is often, but not always, localhost) and the database’s name. If any of these are incorrect, you won’t be able to connect. Depending on the script, either you will see an ugly string of error messages or, if the developer has handled this gracefully, you will be told that the script was unable to connect to the database.
The database connection issues that I commonly see when providing technical support are as follows:
  • The user has entered localhost instead of an IP address or URL for the database server.Localhost means that the database is on the same server as your website. Some hosts have different servers for MySQL and so will give you an address for the server that you need to use when configuring the script.
  • An incorrect user name has been entered.One thing to watch is that cPanel prefixes user names that you create with the account’s name. If your account’s name is fred and you create a user named website, then the user name to enter when configuring a script would be fred_website.
  • An incorrect database name has been entered.As with user names, cPanel prefixes the database’s name with the account’s name. Check that you are using the prefixed version in your configuration.

Database Permission Problems

Another possible cause of database-related trouble is when all of the connection details are correct, but the database user doesn’t have the permissions needed to do things that the script needs to do. For example, the script might need to create database tables and so would require the database user to have create permissions.
If you created the database user in cPanel, you would also need to select the database and join the user to it, giving the user enough permissions to run the script. For example, if you were installing WordPress, your database user would need to have All Privileges for the database it is attached to.
In cPanel, you can set these in the section named “Add user to database.” Select the user and database, and then on the next screen, click the “All Privileges” checkbox before submitting the form.
screenshot

PHP Errors

The next set of errors are those generated by PHP because of some problem with the script that you’re installing or because of something that was introduced while you were installing or configuring it.

Fatal Error: Call to Undefined Function

1Fatal error: Call to undefined function my_function() in /home/mysite/public_html/test.php on line 2
This means that a PHP function that the current page needs cannot be found. The function might be part of the script itself or built right into PHP. You might see this error when installing a third-party script for the following reasons:
  • If you’re installing a new script, you might not have uploaded all of the files. In my experience, people who use Dreamweaver’s FTP client encounter this issue a lot.
  • If you’re upgrading, you might not have replaced all of the required files. So, an old version that doesn’t contain the function is being used.
  • You might not have added a required PHP include or specified a correct path in a configuration file.
  • A script might be calling a PHP function that is not available on this server. For example, it might be calling imagecreatefromjpeg() when the GD image libraries haven’t been installed.
To solve the error, check carefully that all of the files have been uploaded or replaced and that you have followed the installation instructions. If you cannot resolve it, then contact the script’s developer, explaining what you have done and what you have checked and copying the error message.
If the issue is that something is missing in your PHP installation, then you might need to contact your hosting provider.

Fatal Error: Cannot Redeclare

1Fatal error: Cannot redeclare my_function() (previously declared in /home/mysite/public_html/runtime.php:14) in /home/mysite/public_html/runtime.php on line 26
This usually means that you have included a file twice. Check everywhere you have edited and check included files to make sure you haven’t duplicated an include.

Fatal Error: Allowed Memory Size Exhausted

1Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 17472 bytes) in /home/mysite/public_html/lib/Image.class.php on line 198
You will typically see this error when trying to upload and process an image, although you might see it for any script that requires a lot of memory to run. The amount of memory that your scripts are allowed to use is set by the hosting provider. On cheap shared hosting plans, these limits are often set very low. If you need to use a script to process large images, contact your provider to see whether you can move to a plan with higher limits.

Permission Errors

1Warning: move_uploaded_file(/home/mysite/public_html/upload/my_cat.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/mysite/public_html/upload.php on line 49
This warning is an example of a permissions error. The script is trying to upload a file to a directory, but the directory doesn’t have enough permissions for the file to be moved to it. The permissions that PHP needs in order to write to a file or directory depend on how the server is configured and whether you are using a Unix or Windows host. The section on “Permission Scheme” in the WordPress Codex is relevant even if you are not using WordPress. However, if you get any kind of “Permission denied” error or warning and can’t fix it simply by changing the permissions for the folder, speak with your hosting provider rather than the developer of the script, because your provider will be able to tell you how to do this.

PHP Warning: Include

1PHP Warning:  include(foo.php): failed to open stream: No such file or directory in /home/mysite/public_html/test.php on line 2
This warning tells you that an include file (included using PHP’s include syntax) was not found. It is a warning rather than an error, because PHP will continue trying to load the page if it cannot find an include.
In PHP, you can include files using include() or require(). If you use require(), then you are telling PHP that this script is vital to running the website, and so PHP will spit out an error if the file is not found, rather than try to continue.
If you get a warning or error message that a file could not be opened, then check that the file referred to in the error message is there and that your path to it is correct. For example, if you have the file /inc/navigation.php, and the page calling this file is in the directory /about, then you would need to include navigation.php with the following include:
1include(../inc/navigation.php); ?>
Omitting the ../ would result in a warning because PHP would not be able to find the file.

In Summary

PHP errors can seem very confusing if you are not a PHP developer, but if you read the error message carefully, you will usually find something that leads you to the root of the problem. Most of the errors I see in technical support have to do with incorrect database connections, missing files or permissions. These are all things that someone with no PHP knowledge can identify and fix themselves, just by learning how to access error messages and becoming familiar with what PHP is saying in them. Being able to debug these kinds of problems will save you a lot of frustration and will free you from having to wait for tech support to get back to you.
If you run into an error when installing a script, remember the following:
  1. Learn how to access PHP errors on your server.
  2. Look at the error log to see what the error actually is.
  3. See if you can identify the source of the problem by looking at the initial error message or warning for the script.
  4. If the error seems to involve permissions or an incorrect database configuration, open a ticket with your hosting provider.
  5. If the script is the problem, then open a ticket with the developer, explaining what you have done and copying information from the error log. You will bring joy to their heart if you provide the actual error message rather than say you saw a blank page!

Further Reading

Have you come across a particularly baffling error when installing a script? Have you come across a hosting provider that requires a different method to get error logs working? Add your suggestions in the comments section.

Monday, November 21, 2011

Optimizing Error Pages: Creating Opportunities Out Of Mistakes

In this article, we’ll review a few techniques that will help Web designers and UI professionals improve their error pages in order to engage visitors and improve the experience. As C.S. Lewis said, “Failures are finger posts on the road to achievement.” Website designers should take this to heart.
We’ll focus on error and maintenance pages, from both a tracking and usability perspective. You’ll find examples on how to use analytics and defensive design in order to optimize the user experience on those pages.
First, let’s go over error pages and how to optimize them. We’ll try to answer the following questions:
  • Does your 404 page succeed in engaging visitors, who are already frustrated from not finding what they came for?
  • How do you decrease the number of people who arrive on your 404 page?
  • How do you monitor 404 page traffic efficiently?
After, we’ll discuss techniques for improving conversion rates, even when the website is under maintenance. Here are some of the questions we’ll consider:
  • How to time maintenance periods wisely?
  • How to increase visitor engagement using a maintenance page?

Optimizing 404 Pages

The topic of improving error messages was thoroughly covered in Defensive Design for the Web, a book written by the 37signals team. They go over 40 guidelines to “prevent errors and rescue customers if a breakdown does occur.” In guideline 16 (page 93), they advise us to customize our “Page not found” error pages, and they offer interesting insight into how to create error pages:
Instead of merely saying a page is not found, your site needs to explain why a page can’t be located and offer suggestions for getting to the right screen. Your site should lend a hand, not kick people when they are down.
Smart things to include on your 404 page:
  1. Your company’s name and logo;
  2. An explanation of why the visitor is seeing this page;
  3. A list of common mistakes that may explain the problem;
  4. Links back to the home page and/or other pages that might be relevant;
  5. A search engine that customers can use to find the right information;
  6. An email link so that visitors can report problems, missing pages and so on.
A while ago, I came across the great examples shared on Smashing Magazine (part 1 and part 2) and was inspired to create my own 404 page. But because understanding and analyzing online behavior is so important, I asked myself, Is what I’ve come up really good? How can I make it better? Below we’ll go over a few techniques to both monitor and optimize 404 pages.
If you do not have a customized 404 page, please refer to this simple explanation of how to set one up.

Monitoring 404 Page Traffic

How often do you check the traffic to your 404 page? Most of the companies I have worked with never did, even once. Yet it is hard to overemphasize the importance of consistently monitoring it. For example, if a prominent blog links to your website but the link is broken, this will make for a very poor experience for users (who will not find what they expect) and for search engines (which will not crawl the right content). Below are a few tips on tracking those pages seamlessly using Google Analytics. (The screenshots were taken from the new Google Analytics version, which is still in beta, so your mileage may vary.)
Create an alert on Google Analytics.
As seen in the screenshot below, you can set Google Analytics to alert you each time 404 traffic reaches a certain number of visits a day. This way, you have to do the work only once, but you’ll be alerted every time there is a problem.
Google Analytics Alerts
This is where you create a custom alert to track 404 page views.
Track your 404 page as a goal.
Setting the 404 page as a goal on Google Analytics will yield important (and otherwise unattainable) information. For example, you’ll be able to see the three steps that visitors took to get to this page. In addition, setting this goal makes it easier to find traffic sources with broken links.
Google Analytics Goal
Create a goal to track 404 page views in your reports.
Add the 404 content report to your dashboard.
Every report in Google Analytics can be added to the dashboard. By adding the 404 page, you will be able to constantly monitor visitor trends on the page.
Google Analytics Dashboard
Add a 404 goal to your dashboard.
Check your navigation summary report.
This will help you understand what visitors do upon leaving this page, which is important for knowing how to optimize it.
Google Analytics Navigation Summary
The navigation summary for a 404 page on Google Analytics.
Track internal searches from this page.
If your 404 page does not have a search box, seriously consider adding one. From searches performed on this page, you will be able to understand what people were expecting to find, and you will get an idea of what links to add to the page. Below are the metrics you will be able to track with this feature:
  1. Total unique searches
    The number of times people started a search from the 404 page. Duplicate searches from a single visit are excluded.
  2. Search result page views after searches
    The average number of times visitors viewed a search results page after performing a search.
  3. % search exits
    The percentage of searches that resulted in an immediate exit from your website.
  4. % search refinements
    The percentage of searches that resulted in a new search using a different term.
  5. Time after search
    The average amount of time visitors spend on your website after performing a search.
  6. Search depth
    The average number of pages that visitors viewed after performing a search.

Decrease Your Errors (Fixing Broken Links)

Monitoring 404 pages is important, but that alone won’t do you any good unless you act on it. Taking action means doing all you can do to decrease the number of people who reach the 404 page and improving the experience of users who do reach it (see the next section). Below are a few tips on finding and fixing both internal and external broken links.
Check the navigation summary report.
This will show you the route that visitors took on your website to get to the 404 page (and thus tell you which pages contain broken internal links). You will see the percentage of visitors who arrived on this page from internal sources as well as from external sources; and the internal sources will be listed in this report (see the navigation summary screenshot above).
Check the sources of traffic that lead to the 404 page.
This will clearly show which websites have broken links to your website. With the list, you should either contact the sources or create 301 redirects to the correct pages.
Google Analytics Landing Pages
Traffic sources that lead visitors to a 404 page.

Usability Tips to Improve 404 Engagement

Basically, usability practices for error pages are not much different from general usability practices. Below are a few tips to help you increase the conversion rate of your 404 page. For our purpose, conversion is essentially the click-through rate (CTR), because our main objective is for visitors to find what they’re looking for.
  1. Be simple and focused.
    Appealing images and an original design are important, but a clear focus is critical. Users are already disoriented from landing somewhere they were not expecting, so make their lives easier by presenting a clear action to take.
  2. Know your visitors.
    Many 404 pages use humor, including geek humor. Keep in mind that you are not your visitor, and jokes can be misunderstood, so use humor wisely.
  3. Let the visitor decide.
    As I said in “Web Analytics Process”: “Customers should tell us what to do, not consultants, friends or feelings; data and online surveys are the place to look for customers’ needs.” The best way to understand what works for visitors is to present a few page versions and let the best one win. (See the review of advanced A/B testing techniques by Paras Chopra.)

Optimizing Maintenance Pages

Not long ago, I worked on a website that had weekly downtime for maintenance, about one to two hours a week. The owners chose the day with the least traffic for maintenance, but I believe they did not completely understand how this affected the website and, more importantly, how they could have optimized the user experience and taken advantage of the downtime.

  1. Keep the maintenance page simple and useful.
  2. Realize it’s an inconvenience to visitors.
  3. Don’t be afraid to use humor.
  4. Give the page the same look and feel as the rest of your website.
  5. Let visitors know when the website will be back up.
  6. Recommend content.
  7. Invite visitors to return when the website is online again.
  8. Inform visitors about the progress of the maintenance.
Two other rules are especially important to satisfy and engage visitors…

Time Maintenance Periods Wisely

Common practice for timing maintenance is to choose the time of day or day of week that has the lowest traffic. But this overlooks an important point: websites should be optimized for performance, not for traffic. By choosing the maintenance time based on visitor count, you could be optimizing for traffic and not for dollars. A better way to decide would be to run an hourly report and check what time of day or day of week has the lowest conversions.

Increase Visitor Engagement Using Maintenance Pages

Increase visitor engagement while the website is in maintenance mode? Yes, you read that right. While in maintenance, you have a great opportunity to promote your other marketing channels: offline stores, Facebook fan pages, YouTube channels and Twitter accounts.
Maintenance Page Example
The maintenance page for Online Behavior.

Parting Thoughts

Errors happen, and we must be prepared for them. We must lend a hand when visitors are most frustrated and make them feel comfortable again. People’s patience and understanding are decreasing, and users have a world of choices just a click away, so website owners cannot let one small error get in their way.
What are your thoughts on this subject? Feel free to share them with us in the comment section below!