REST API & Developer PHP Advanced

Only Allow REST API Requests From Your Own Domains

Replace WordPress's "any origin" CORS headers with a list of domains allowed to call your REST API from a browser.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 23 lines
add_action( 'rest_api_init', function (): void {
	remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );

	add_filter( 'rest_pre_serve_request', function ( $served ) {
		$allowed = [
			home_url(),
			'https://app.example.com',
		];
		$allowed = array_map( fn ( string $url ): string => untrailingslashit( set_url_scheme( $url, 'https' ) ), $allowed );

		$origin = get_http_origin();

		if ( $origin && in_array( untrailingslashit( set_url_scheme( $origin, 'https' ) ), $allowed, true ) ) {
			header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
			header( 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' );
			header( 'Access-Control-Allow-Credentials: true' );
			header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type' );
			header( 'Vary: Origin', false );
		}

		return $served;
	} );
}, 15 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WordPress answers REST API requests from any website with CORS headers that allow the browser to read the response. For public data that’s fine, but if your API serves logged-in users to a separate app, you may want to limit which sites can call it from the browser.

How it works

WordPress sends CORS headers through rest_send_cors_headers(), which echoes back whatever Origin the browser sends. The snippet removes that and adds its own version, which only sends Access-Control-Allow-Origin when the origin is in your list.

Origins are compared on scheme and host, with trailing slashes removed. Vary: Origin tells caches that the response depends on who asked.

Things to watch

  • CORS only affects browsers. Server-to-server requests, curl and mobile apps aren’t limited by it. Use authentication to protect private data.
  • Add every front end that needs the API, including staging domains.
  • Some plugins, like WooCommerce Blocks, call the REST API from your own domain, which is always in the list.

How to test it

From an allowed site’s browser console, run fetch('https://yoursite.com/wp-json/'). It should work. From any other site it should fail with a CORS error.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only