50

I am considering to improve security of my Wordpress website, and in doing so have come across WP REST API being enabled by default (since WP 4.4 if I'm not mistaken).

What is a safe way to disable it?

By "safe" here I mean that it does not cause unexpected side-effects, e.g. does not break any other WP core functionality.

One possible approach would be to use .htaccess rewrite rules, but surprisingly I haven't found any 'official' instructions on doing so.

Any help or recommendation is greatly appreciated :)

Update: 3rd-party plugins is not the solution I am looking for. Although I'm aware there are plenty of them that solve the task, they include many extra features that slow down the website. I would hope there is a one-line solution to this problem without the overhead of an extra plugin.

Update 2: Here is the official opinion of Wordpress: https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-disable-the-rest-api

According to this, the Wordpress team wants future WP functionality to depend on the new REST API. This means there is no guaranteed safe way to disable the REST API.

Let's just hope there are enough security experts taking care of WP security.

Update 3:

A workaround is presented in WordPress API Handbook - you can Require Authentication for All Reque​sts

This makes sure that anonymous access to your website's REST API is disabled, only authenticated requests will work.

8 Answers 8

47

From the author original question I've chosen option 2 that came from wordpress official recommendations(https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-disable-the-rest-api). So just put in your functions.php to let only logged in users use the rest api (but just cross check original link in case my code block is outdated ;) ): UPD(01-10-2021):

add_filter( 'rest_authentication_errors', function( $result ) {
    // If a previous authentication check was applied,
    // pass that result along without modification.
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    // No authentication has been performed yet.
    // Return an error if user is not logged in.
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            __( 'You are not currently logged in.' ),
            array( 'status' => 401 )
        );
    }

    // Our custom authentication check should have no effect
    // on logged-in requests
    return $result;
});
8
  • 1
    @EricGopak Sure. I adopted that in my blog. If you are logged out and accessing https://{your-host}/wp-json/wp/v2/posts/{post_id} u'll get this error msg -> { "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } } Otherwise u'll get proper json response with post data in it. Nov 21, 2018 at 9:48
  • 1
    Cool, thanks! I'll take it as the correct answer then :)
    – Eric Gopak
    Nov 23, 2018 at 16:04
  • 1
    @DzmitryHubin - Is there a way to limit the requests to a specific user? If yes how and what impact would this have to services reliant on the API e.g. WordPress' Site Health check, Gutenberg, etc? I posted a question on the WordPress forum (wordpress.stackexchange.com/questions/344989/…) so hopefully you may be able to assist
    – Motivated
    Aug 13, 2019 at 8:44
  • 1
    @DzmitryHubin the code was updated on WP side, maybe you should update your answer.
    – 8ctopus
    Sep 28, 2021 at 10:54
  • 1
    @8ctopus done. Thanks for reminder and have a nice day bro! Oct 1, 2021 at 9:01
20

The accepted answer disables all API calls from unauthenticated users, but nowadays lot of plugins are dependent on this API's functionality.

Disabling all calls will lead to unexpected site behavior which happened in my case also when I used this code.

For example, ContactForm7 makes use of this API for sending contact info to DB (I think) and for ReCaptcha validation.

I think it would be better to disable some (default) endpoints for unauthenticated users like this:

// Disable some endpoints for unauthenticated users
add_filter( 'rest_endpoints', 'disable_default_endpoints' );
function disable_default_endpoints( $endpoints ) {
    $endpoints_to_remove = array(
        '/oembed/1.0',
        '/wp/v2',
        '/wp/v2/media',
        '/wp/v2/types',
        '/wp/v2/statuses',
        '/wp/v2/taxonomies',
        '/wp/v2/tags',
        '/wp/v2/users',
        '/wp/v2/comments',
        '/wp/v2/settings',
        '/wp/v2/themes',
        '/wp/v2/blocks',
        '/wp/v2/oembed',
        '/wp/v2/posts',
        '/wp/v2/pages',
        '/wp/v2/block-renderer',
        '/wp/v2/search',
        '/wp/v2/categories'
    );

    if ( ! is_user_logged_in() ) {
        foreach ( $endpoints_to_remove as $rem_endpoint ) {
            // $base_endpoint = "/wp/v2/{$rem_endpoint}";
            foreach ( $endpoints as $maybe_endpoint => $object ) {
                if ( stripos( $maybe_endpoint, $rem_endpoint ) !== false ) {
                    unset( $endpoints[ $maybe_endpoint ] );
                }
            }
        }
    }
    return $endpoints;
}

With this, the only endpoints now open are the ones installed by the plugins.

For complete list of endpoints active on your site, see https://YOURSITE.com/wp-json/

Feel free to edit $endpoints_to_remove array as per your requirement.

If you have custom post type, make sure to add those all to the list too.

In my case, I also changed the default endpoint prefix from wp-json to mybrand-api. This should act a deterrent for bots that were making thousands of brute-force requests.

Here is what I did:

// Custom rest api prefix (Make sure to go to Dashboard > Settings > Permalinks and press Save button to flush/rewrite url cache )
add_filter( 'rest_url_prefix', 'rest_api_url_prefix' );
function rest_api_url_prefix() {
    return 'mybrand-api';
}
6
  • Thanks for this! I find this highly customizable and works like a charm.
    – Albion
    Feb 9, 2021 at 2:10
  • 1
    This seems to disable the listed rest api endpoints for not logged in and logged in users. At least through browser requests.
    – chris
    Dec 29, 2021 at 1:28
  • Testing through nonce authentication seems to work as expected. So it's just cookie authentication that is ignored.
    – chris
    Dec 29, 2021 at 1:48
  • @Anand, this is super helpful although it's manual and each time there's a change to the custom post type, it has to be updated.
    – Motivated
    Sep 14, 2022 at 4:18
  • @Anand, what unexpected site behavior did you experience?
    – Motivated
    Sep 14, 2022 at 4:19
15

You can disable it for requests other than localhost:

function restrict_rest_api_to_localhost() {
    $whitelist = [ '127.0.0.1', "::1" ];

    if( ! in_array($_SERVER['REMOTE_ADDR'], $whitelist ) ){
        die( 'REST API is disabled.' );
    }
}
add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 0 );
9
  • @HarryBosh it shouldn't, since it's in functions.php Nov 27, 2018 at 1:24
  • Only plugins and themes are immune - wordpress.stackexchange.com/questions/230716/…
    – Harry Bosh
    Nov 27, 2018 at 1:33
  • 1
    ok so your not talking about /wp-includes/functions.php guess that is clarified now...
    – Harry Bosh
    Nov 28, 2018 at 3:03
  • 3
    @HarryBosh when someone references functions.php in wordpress they're almost always talking about the theme's functions.php Dec 11, 2018 at 19:33
  • 1
    It's good but in my case I had to add "fe80::1" to whitelist as well.
    – Navidot
    Apr 25, 2019 at 21:06
14

Disabling REST API was not a bad idea, after all. It actually opened a huge hole in all websites!

In wordpress 4.4 there was a way

Here, I've found a possible solution with .htaccess but should be carefully tested in combination with whatever else is in your .htaccess file (e.g., pretty-url rules added by wordpress itself):

# WP REST API BLOCK JSON REQUESTS 
# Block/Forbid Requests to: /wp-json/wp/
# WP REST API REQUEST METHODS: GET, POST, PUT, PATCH, DELETE
RewriteCond %{REQUEST_METHOD} ^(GET|POST|PUT|PATCH|DELETE) [NC]
RewriteCond %{REQUEST_URI} ^.*wp-json/wp/ [NC]
RewriteRule ^(.*)$ - [F]

A very drastic method, is also to have a 404.html webpage in your root and then add this line:

# WP REST API BLOCK JSON REQUESTS 
# Redirect to a 404.html (you may want to add a 404 header!) 
RewriteRule ^wp-json.*$ 404.html

Note that, unless you use a static page, i.e., not involved with wordpress functions, if you want to return a 404 error with an appropriate error page, this is a complete separate topic, with a lot of issues when Wordpress is involved

8
  • Thank you for the answer! Would be really nice if you could test it, before I accept your answer. A question though: why would you want to trick bots? And which bots do you think are going to crawl /wp-json?
    – Eric Gopak
    Feb 3, 2017 at 13:15
  • I mean, I've tested the second option and it works on my setup. The first does not, but I think there is some issue with other .htaccess rules I have
    – Kuzeko
    Feb 4, 2017 at 7:43
  • The malicious bots, those that can automatically test for errors and holes in your WP installation.
    – Kuzeko
    Feb 4, 2017 at 7:44
  • In my opinion, malicious bots are not so easily fooled as by simple HTTP status code (they can easily check contents of server response). I would prioritize being honest with indexing bots (e.g. GoogleBot) so that it never actually indexes /wp-json even if it happens to have an incoming link. HTTP status code 404 fits well here, I think.
    – Eric Gopak
    Feb 5, 2017 at 11:01
  • 1
    for nginx: location ~ ^/wp-json/ { return 404; }
    – minaz
    Oct 31, 2018 at 7:04
2

if you want to disable Wordpress REST API completely use this code:

// Disable Wordpress REST API
remove_action( 'init', 'rest_api_init' );
remove_action( 'rest_api_init', 'rest_api_default_filters', 10 );
remove_action( 'rest_api_init', 'register_initial_settings', 10 );
remove_action( 'rest_api_init', 'create_initial_rest_routes', 99 );
remove_action( 'parse_request', 'rest_api_loaded' );
2
  • After adding this code I couldn't add a new Post from the backend. May 12, 2021 at 7:27
  • 1
    this code disable wordpress reset api completely include gutenberg api. so you can use classic editor or you should use @Dzmitry Hubin code to just limit reset api to logged in users or custom roles May 12, 2021 at 11:19
1

With the plugin "Disable REST API" you can select which APIs you want to enable, e.g. the contact form 7 API. See the plugin's settings (yoursite.com/wp-admin/options-general.php?page=disable_rest_api_settings)

1
  • 4
    It would be a good practice not to use a plugin for each small thing, that may be achieved with a small filter function or some lines in .htaccess. Dec 26, 2018 at 16:50
0
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
2
  • Did not work for me, although I also found this lines on other blogs.
    – remy
    Apr 13, 2022 at 12:02
  • It's for WordPress < 4.7
    – Olivier C
    Aug 15, 2022 at 11:15
0

There are several points you need to "turn off". Also, you might want to place some kind of notice to someone coming to that page...

Here is what I used (and was checked):

function itsme_disable_feed() {
    wp_die( __( 'No feed available, please visit the <a href="http://www.example.co.il">Example</a>!' ) );
}

add_action('do_feed', 'itsme_disable_feed', 1);
add_action('do_feed_rdf', 'itsme_disable_feed', 1);
add_action('do_feed_rss', 'itsme_disable_feed', 1);
add_action('do_feed_rss2', 'itsme_disable_feed', 1);
add_action('do_feed_atom', 'itsme_disable_feed', 1);
add_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);
add_action('do_feed_atom_comments', 'itsme_disable_feed', 1);

As per wp_die() docs:

This function complements the die() PHP function. The difference is that HTML will be displayed to the user. It is recommended to use this function only when the execution should not continue any further. It is not recommended to call this function very often, and try to handle as many errors as possible silently or more gracefully.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.