Hack: Create a Simple 404 Log

When someone links to your site with the wrong URL, or, worse, you link to your own site with the wrong URL, it would be nice to know. You could check your server’s logs for 404 errors to see what bad URLs people are using. But I find it easier to create a simple 404 log file that I can access without much hassle. Then I check it every once in a while to see if I need to add a redirect to the correct page so I don’t miss some traffic.

A simple way to do this is to add a few lines of code to the end of your 404.php page in your theme. Make a child theme first, unless the theme is already your own custom one. Then add this code to the very end.

if ($f = fopen(get_home_path().'logs/404log.txt','a')) {
	fwrite($f,date("Y-m-d H:i:s")."\t".$_SERVER['REQUEST_URI']."\n");

In this example I’m assuming there is a logs directory at the main level of your site. It will create the file 404log.txt there provided the permissions for the directory allow it. Then you can easily check this text file to see what is going on.

When I first created something like this years ago it was a revelation. I found a bunch of links to my site with typos in them. I was able to add some redirects in .htaccess to send the traffic to the right place. You can use this tip to redirect as well.

Leave a Reply

Your email address will not be published. Required fields are marked *