Prevent External Access to Wordpress Rest API

Its very easy for a malicious actor to see a list of the usernames used on your wordpress installation if you have not locked that information down.

Use the code below in your functions.php file to hide external requests to your rest api.

EG: https://www.yourdomainname.com/wp-json/wp/v2/users/

The script below will close off the rest API from /wp-json/ and only allow local access to it.

########################
// Prevent external reading of json api
// See: https://www.jucra.com/whmcs/knowledgebase/183/
########################
function restrict_rest_api_to_localhost() { 
       
        $whitelist = [ '127.0.0.1', "::1" ];
        $message = "REST API is disabled.";
       
      if( ! in_array($_SERVER['REMOTE_ADDR'], $whitelist ) ){ 
          die( $message ); 
      } 
} 
 
add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 0 );
  • wordpress, rest api, security, secure wordpress, lockdown wordpress
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

customised wordpress wp-config file

Out of the box, the WordPress wp-config.php file is basic and ugly.Below is our standard...

Fix WordPress 404 Errors on Password Protected Directories

You are reading this article becasue you have applied password protection on the wp-admin...

Enable Fenced Off Debugging to Your IP in Wordpress

Use the code below to activate the bugging in WordPress but locked down to your IP.Put this in...

How to protect your Wordpress Login from Bots

You are reading this article because you are getting a lot of attacks on your WordPress login...

SVG Logo is not appearing in Wordpress

You are reading this article because you have managed to upload an SVG file to your Wordpress...