One of the great things about WordPress is how 404 error pages are handled. If a page isn’t found then you can show a proper dynamic error page giving the user things to do – this removes a lot of the traditional problems with 404 pages, ie the dead end syndrome.
404 is the server error code that is generated for content that doesn’t exist.
However these new 404 pages are a lot slower than normal 404’s, they require database contact, and PHP processing so if you have a lot of them they can slow down your server. Most times the benefits outweigh the negatives however there is one time when this isn’t the case.
Images and other media that are not loaded, do not need a full 404 page. If you’re linking to an image that doesn’t exist then you could create a lot of extra work for your web server.
How to make it work
To stop the 404 page from executing fully I look at the url and work out if it’s a url for a blocked file type (jpg, css, js, etc). If the file is in the list of bad file types then it gets stopped and a message is displayed.
function bm_404Response() {
header('HTTP/1.1 404 Not Found');
if (!empty($_SERVER['REQUEST_URI'])) {
$fileExtension = strtolower(pathinfo($_SERVER['REQUEST_URI'], PATHINFO_EXTENSION));
} else {
$fileExtension = '';
}
$badFileTypes = array(
'css', 'txt', 'jpg', 'gif', 'rar', 'zip', 'png', 'bmp', 'tar', 'doc', 'xml', 'js',
);
$badFileTypes = apply_filters('bm_404BadFileTypes', $badFileTypes);
if (in_array($fileExtension, $badFileTypes)) {
echo 'error - file does not exist';
die();
}
}
Where to use it
This function should be added to your themes functions.php file. To execute it I placed it at the top of my 404.php template page, however in hindsight I could probably also use an action instead and may just tweak my theme to use that instead. There’s nothing like writing about something to make the problems clear! 🙂
Do you have any ideas for other things I could do to improve this code? Do you think it’s a good idea?
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.