Block IP Addresses That Trigger Many 404 Errors
Temporarily blocks visitors who hit more than 20 missing pages within a minute, a typical sign of vulnerability scanners probing for old plugins and backup files.
Opens WPIDE on
Code
// 404 errors allowed per minute, and how long offenders are blocked (minutes).
$wpide_404_limit = 20;
$wpide_404_block = 60;
$wpide_404_key = function () {
return md5( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '' );
};
add_action( 'init', function () use ( $wpide_404_key ) {
if ( is_admin() || is_user_logged_in() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
if ( get_transient( 'wpide_404_ban_' . $wpide_404_key() ) ) {
status_header( 403 );
nocache_headers();
exit( 'Too many requests for missing pages. Try again later.' );
}
}, 1 );
add_action( 'template_redirect', function () use ( $wpide_404_key, $wpide_404_limit, $wpide_404_block ) {
if ( ! is_404() || is_user_logged_in() ) {
return;
}
$key = 'wpide_404_count_' . $wpide_404_key();
$count = (int) get_transient( $key ) + 1;
set_transient( $key, $count, MINUTE_IN_SECONDS );
if ( $count > $wpide_404_limit ) {
set_transient( 'wpide_404_ban_' . $wpide_404_key(), 1, $wpide_404_block * MINUTE_IN_SECONDS );
}
}, 99 );
Notes
Logged-in users are never blocked; raise $wpide_404_limit if you recently changed many URLs and expect lots of broken links.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.