Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.