How to detect and redirect 404 errors

To prevent your visitors from seeing the 404 page too often, it can be useful to keep track of the URLs that produce 404 errors in the first place.