Halloween Sale 15% off Ends in See the plans
PHP

Rate-Limit the REST API for Visitors

Limits how many REST API requests a logged-out visitor can make per minute and answers "429 Too Many Requests" beyond that, slowing scrapers and scanners.

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

Code

// Requests per minute per IP address for logged-out visitors.
$wpide_rest_limit = 120;

add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) use ( $wpide_rest_limit ) {
    if ( null !== $result || is_user_logged_in() || empty( $_SERVER['REMOTE_ADDR'] ) ) {
        return $result;
    }

    $key  = 'wpide_rest_' . md5( (string) $_SERVER['REMOTE_ADDR'] . '|' . floor( time() / 60 ) );
    $hits = (int) get_transient( $key ) + 1;
    set_transient( $key, $hits, 2 * MINUTE_IN_SECONDS );

    if ( $hits > $wpide_rest_limit ) {
        return new WP_Error( 'wpide_rate_limited', 'Too many requests. Please slow down.', array( 'status' => 429 ) );
    }

    return $result;
}, 10, 3 );

Notes

Writes a short-lived transient per visitor per minute; use it with a persistent object cache on busy sites.

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.