Search code examples
wordpress.htaccesswordpress-rest-api

Disable WordPress routes except for the JSON API and admin UI


I'm planning to use my WordPress installation as a headless and only consume data via WP API (https://developer.wordpress.org/rest-api/reference/) in the front-end.

But by default, the UI of the client-facing website is visible to all the users and I want to make sure that if a customer opens a website it gets redirected to my front end.

To make it clear, here's examples:

  • open: wordpress-example.com -> redirect to my-api-example.com
  • open: wordpress-example.com/any-route -> redirect to my-api-example.com etc.
  • open: wordpress-example.com/wp-json/wp/v2/posts -> return API response
  • open: wordpress-example.com/wp-json/wp/v2/categories -> return API response etc.
  • open: wordpress-example.com/wp-admin.php -> opens WP Admin

Solution 1: Maybe there is a global setting in WordPress or a separate plug-in that disables the UI. I could not find it.

Solution 2: Adjust the .thaccess file to exclude /wp-admin.php and /wp-json/ routes https://fedingo.com/how-to-exclude-folder-from-rewrite-rule-in-htaccess/


Solution

  • place a redirect at the beginning of your header.php file

    $parts = parse_url( home_url() );
    $current_uri = "{$parts['scheme']}://{$parts['host']}" . add_query_arg( NULL, NULL );
    $url_parsed = wp_parse_url($current_uri);
    $new_url = 'https://my-api-example.com' . $url_parsed['path'];
    wp_safe_redirect($new_url);
    exit;