Safely disable WP REST API

后端 未结 5 1748
花落未央
花落未央 2021-01-30 13:37

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).

5条回答
  •  旧时难觅i
    2021-01-30 14:11

    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';
    }
    

提交回复
热议问题