The WordPress REST API can expose sensitive information like usernames. This guide shows how to restrict it for unauthenticated users while keeping it functional for the WordPress admin and Gutenberg editor.
Method 1: Require Authentication for All REST API Requests
Add this to your theme's functions.php or a custom plugin:
add_filter('rest_authentication_errors', function($result) {
if (true === $result || is_wp_error($result)) {
return $result;
}
if (!is_user_logged_in()) {
return new WP_Error(
'rest_not_logged_in',
'You are not currently logged in.',
array('status' => 401)
);
}
return $result;
});
This blocks all REST API access for non-logged-in users. Gutenberg and admin features continue to work normally because they are authenticated requests.
Method 2: Disable Only User Enumeration
If you want to keep the REST API accessible but prevent user enumeration specifically:
add_filter('rest_endpoints', function($endpoints) {
if (isset($endpoints['/wp/v2/users'])) {
unset($endpoints['/wp/v2/users']);
}
if (isset($endpoints['/wp/v2/users/(?P<id>[\d]+)'])) {
unset($endpoints['/wp/v2/users/(?P[\d]+)']);
}
return $endpoints;
});
Method 3: Remove the REST API Link from HTML
To hide the REST API URL from the HTML source (the <link rel="https://api.w.org/"> tag):
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('xmlrpc_rpc_methods', 'rest_output_link_wp_head');
remove_action('template_redirect', 'rest_output_link_header', 11);
Verify with InspectWP
After implementing your changes, run a new InspectWP scan. The REST API section should reflect your changes — either showing the API as not accessible or the user endpoint as restricted.