https://example.com/wp-json/wp/v2/users returns your publishing authors — display names, login slugs, author archive URLs — to anyone who asks, and there is no setting in wp-admin that turns it off. The fix that works without breaking the site is a short must-use plugin on the rest_authentication_errors filter. That filter runs once per REST request, after WordPress has resolved who the caller is and before route dispatch, so it catches /wp-json/... and ?rest_route=... with the same line of code, and it lets you allowlist the handful of namespaces a logged-out visitor genuinely needs: WooCommerce’s Store API, your contact form, oEmbed. The two approaches that do break things are blanket .htaccess denies on /wp-json and rest_endpoints unset tricks — the first misses half the traffic, the second takes the endpoint away from your own editor too.
What you’ll accomplish
- A measured inventory of what your site hands an anonymous REST client today, namespace by namespace.
- A must-use plugin that returns
401to logged-out REST callers at a single hook, with an explicit allowlist. - Front-end forms, guest checkout and oEmbed still working, because their namespaces are on that list.
- The REST discovery
Linkheader, thewp_headdiscovery tag and the RSD tag removed. - curl checks that prove the policy, both logged out and with an application password.
Prerequisites
WordPress 4.7 or newer (the REST API is core from 4.7 on), and 5.6 or newer if you want to test with application passwords, which is the sane way to verify the authenticated path. Application passwords also require HTTPS, so test on a site with a real certificate rather than a plain-HTTP staging box.
You need write access to wp-content/mu-plugins/ and, ideally, WP-CLI. Note what must-use plugins are before you use one: WordPress loads every top-level .php file in that directory before regular plugins, they cannot be deactivated from wp-admin, and files in subdirectories are ignored. That is exactly what you want for a security policy, and it also means a mistake here is only fixable with file access. Do this on staging first.
Locally you need curl and jq. Every command below assumes example.com is your site.
How it works
WordPress serves REST requests through one entry point. Both public URL forms — the pretty /wp-json/wp/v2/users path, which exists only because of a rewrite rule, and /?rest_route=/wp/v2/users, which works even with plain permalinks — end up setting the same rest_route query variable. rest_api_loaded() sees that variable and hands the path to WP_REST_Server::serve_request(). That method calls check_authentication(), which applies the rest_authentication_errors filter, and only if the filter did not produce a WP_Error does it go on to dispatch(), where the route is matched and its permission_callback runs.
Three consequences make this the right hook. It runs after determine_current_user, so cookie sessions, application passwords and plugin-supplied authentication have already resolved — is_user_logged_in() inside the filter tells you the truth. It runs before dispatch, so a denied request never touches a controller, a database query or a plugin’s permission callback. And it sees the normalised route, not the raw URL, so the ?rest_route= form cannot slip past the way it slips past a path-based rewrite rule.
What that request path exposes to a logged-out caller, on stock WordPress:
/wp-json/— the index: site name, description, home URL, thenamespacesarray, and every registered route with its methods and accepted arguments. It is a free map of your plugin stack.wp/v2/users— authors who have published at least one post in a REST-visible post type. Core withholds users with no published posts, which is the one restraint it applies. For the rest you getid,name,slug(the nicename, which on most installs is the login),link(the author archive),descriptionandavatar_urls. Pagination is advertised in theX-WP-TotalPagesheader, so “only ten results” is not a limit.wp/v2/posts— published posts only. Core does not hand drafts to anonymous callers;?status=draftis refused. What does leak is registered post meta declared withshow_in_rest, which appears in themetaobject on public reads, and custom post types registered aspublicwithshow_in_restthat were only ever meant for internal use.wp/v2/media— every attachment in the library with its full-size URL andmedia_details, including files uploaded and never placed on a page.wp/v2/comments— approved comments withauthor_name,author_urland an avatar URL containing an MD5 of the commenter’s address. The address itself needseditcontext, so it does not leak directly.- Discovery — a
Linkheader withrel="https://api.w.org/"on every front-end response, the same pointer as awp_headtag, and the RSDEditURItag whose document advertises the API URL next to XML-RPC.
The part that decides your policy is which namespaces a logged-out human actually needs.
wc/store is the one people close by accident: WooCommerce’s Store API powers the cart and checkout blocks for guests, who by definition are not logged in. Contact Form 7 posts submissions to contact-form-7/v1. oembed/1.0 is how other sites embed your posts. The block editor is not on this list, because editors are logged in — a blanket policy that exempts logged-in users never touches it.
Step-by-step
-
Inventory before you change anything. Do this first: once the policy is on,
/wp-json/itself returns401and you can no longer enumerate anonymously.curl -s https://example.com/wp-json/ | jq -r '.namespaces[]' curl -s 'https://example.com/wp-json/wp/v2/users?per_page=100' | jq -r '.[].slug' curl -sD - -o /dev/null 'https://example.com/wp-json/wp/v2/users' | grep -i x-wp-totalThe first prints one namespace per line — expect
oembed/1.0,wp/v2,wp-site-health/v1and whatever your plugins add. The second prints your login slugs; if it does, the site is enumerable. The third gives the true author count, not the first page.From the server, list the registered routes rather than guessing:
wp eval 'print_r( array_keys( rest_get_server()->get_routes() ) );' -
Write the must-use plugin. Create
wp-content/mu-plugins/rest-api-policy.php:<?php /** * Plugin Name: REST API policy - authentication required, with allowlist */ add_filter( 'rest_authentication_errors', function ( $result ) { if ( null !== $result ) { return $result; } if ( is_user_logged_in() ) { return $result; } $raw = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? $GLOBALS['wp']->query_vars['rest_route'] : '/'; $route = '/' . trim( $raw, '/' ); if ( '/' !== $route ) { $route .= '/'; } $public_prefixes = array( '/oembed/1.0/', '/wc/store/', '/contact-form-7/', ); foreach ( $public_prefixes as $prefix ) { if ( 0 === strpos( $route, $prefix ) ) { return $result; } } return new WP_Error( 'rest_not_logged_in', 'REST API access on this site requires authentication.', array( 'status' => 401 ) ); }, 99 );Priority
99matters: authentication providers hook the same filter and returntruewhen they have authenticated a caller, and thenull !== $resultguard passes their verdict through untouched. Reload the site — a normal page must still render, because this filter only fires on REST requests. -
Tune the allowlist to your own site. Delete prefixes you do not run;
wc/storeon a site without WooCommerce is dead weight. To find the namespace a front-end feature depends on, open the page in a browser with the network panel filtered towp-json, submit the form, and read the path. Grep works too:grep -rho "register_rest_route( *'[^']*'" wp-content/plugins/ | sort -uAdd prefixes one at a time and re-test the feature after each. An over-broad allowlist quietly reopens what you just closed.
-
Or close only user enumeration. If a blanket policy is too disruptive, scope the same filter to the users routes:
add_filter( 'rest_authentication_errors', function ( $result ) { if ( null !== $result || is_user_logged_in() ) { return $result; } $raw = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? ltrim( $GLOBALS['wp']->query_vars['rest_route'], '/' ) : ''; if ( 0 !== strpos( $raw, 'wp/v2/users' ) ) { return $result; } return new WP_Error( 'rest_user_enumeration_blocked', 'User listings are not public on this site.', array( 'status' => 401 ) ); }, 99 );Be aware of the hole this leaves.
?_embedon a posts request makes WordPress resolve the author link internally, throughrest_do_request(), which never callscheck_authentication()— so the author object comes back anyway. Close it by stripping the identifying fields for anonymous callers as well:add_filter( 'rest_prepare_user', function ( $response ) { if ( is_user_logged_in() ) { return $response; } $data = $response->get_data(); unset( $data['slug'], $data['link'] ); $response->set_data( $data ); return $response; } ); -
Stop advertising the API. Add to the same must-use plugin:
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 ); remove_action( 'template_redirect', 'rest_output_link_header', 11 ); remove_action( 'wp_head', 'rsd_link' );These run at file-load time because core registers them in
default-filters.php, which loads before must-use plugins. This is defence in depth, not a control — the API is still at its conventional URL — but it drops your site out of the scans that only follow advertised endpoints. Leavewp_oembed_add_discovery_linksalone unless you also want to stop other sites embedding your posts. -
Close the name leaks that are not REST. Author archives and the core users sitemap publish the same nicenames. If the site has no real author pages, remove both:
add_filter( 'wp_sitemaps_add_provider', function ( $provider, $name ) { return ( 'users' === $name ) ? false : $provider; }, 10, 2 ); add_action( 'template_redirect', function () { if ( is_author() ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); } } );
Validate it works
Run the closed cases and the allowed cases in one pass:
curl -s -o /dev/null -w '%{http_code}\n' https://example.com/wp-json/wp/v2/users
curl -s -o /dev/null -w '%{http_code}\n' 'https://example.com/?rest_route=/wp/v2/users'
curl -s -o /dev/null -w '%{http_code}\n' https://example.com/wp-json/
curl -s -o /dev/null -w '%{http_code}\n' 'https://example.com/wp-json/oembed/1.0/embed?url=https://example.com/'
Expected: 401, 401, 401, 200. The second line is the one that fails on every naive path-based block, so treat a 200 there as the policy not being in effect. Read the body once to confirm the error is yours:
curl -s https://example.com/wp-json/wp/v2/users | jq -r '.code, .data.status'
Expected: rest_not_logged_in then 401.
Now prove the authenticated path still works. Create an application password under Users, and use it as HTTP Basic credentials — spaces and all, quoted:
curl -s -u 'ops:abcd EFGH ijkl MNOP qrst UVWX' https://example.com/wp-json/wp/v2/users | jq -r '.[].slug'
Expected: your author slugs, from the same URL that returned 401 a moment ago. Then confirm discovery is gone:
curl -sI https://example.com/ | grep -i '^link:'
curl -s https://example.com/ | grep -Eo 'rel="(https://api.w.org/|EditURI)"'
Both should print nothing. Finish in a browser: open the block editor and save a post, submit the contact form logged out in a private window, and add a product to the cart as a guest.
Troubleshooting
The contact form returns 401 after the change. Its namespace is not on the allowlist. Open the form page logged out, submit it with the browser network panel filtered to wp-json, and read the path from the failed request. Security plugins produce the same symptom with their own blunter rules — when a security plugin blocks the REST API covers that side.
The application password gets rest_not_logged_in too. Apache running PHP as CGI or FastCGI drops the Authorization header before PHP sees it, so WordPress never authenticates the caller. Add SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 to the site’s .htaccess, above the WordPress block, and retry. Also confirm the request is over HTTPS: application passwords are unavailable on plain HTTP.
Anonymous requests still return data. Either a full-page cache is serving a response captured before the change — purge it and exclude /wp-json/ from caching — or the file is not loading. Must-use plugins must be top-level files: mu-plugins/rest-api-policy.php loads, mu-plugins/rest-policy/index.php does not. Check with wp plugin list --status=must-use.
Logged-in users get 401 from the editor. A page cache is serving the anonymous 401 to authenticated requests. Exclude /wp-json/ and the rest_route query argument from the cache entirely; REST responses are per-user and should not be cached at the edge without a rule that varies on the login cookie.
Front-end JavaScript breaks on a page with no form. Some themes and blocks fetch wp/v2 for anonymous visitors — search results, post-grid blocks, infinite scroll. The browser console names the route. Either allowlist that route specifically or change the block; do not widen the allowlist to all of wp/v2.
When this is the wrong approach
If the site is headless, or a mobile app or partner integration reads content anonymously, a blanket policy is a rewrite of their auth model, not a hardening step. Give those consumers application passwords or a token plugin first, then close the door.
If the goal is stopping brute force, this is not the control. Hiding usernames raises the cost of an attack; it does not stop credential stuffing, and the names are still in bylines, /author/ URLs, comment threads and anything you have published elsewhere. Treat it as one layer inside a layered brute-force defence with strong passwords, two-factor on administrators, and rate limiting at the edge. A WAF rule capping unauthenticated /wp-json/ requests per IP is a good companion, not a substitute.
If you run a WooCommerce store with the cart and checkout blocks, wc/store cannot be closed at all — it is the storefront. Harden inside it instead: keep WooCommerce current, and do not register custom Store API routes that expose customer data.
And if you were about to close everything with a Deny from all rule on /wp-json, reread the second validation command. It answers on /, carries the route in the query string, and returns the same data your rewrite rule never saw. The full endpoint reference is in the WordPress REST API handbook and the users endpoint reference.
Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.