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.
Opens WPIDE on
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
- 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.