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/
2
Answers
place a redirect at the beginning of your
header.php
fileAt the top of the root
.htaccess
file, before the existing WordPress directives:This assumes both
wordpress-example.com
andmy-api-example.com
resolve to the same place. If not then you can remove the preceding condition (RewriteCond
directive) that checks the requestedHost
header.The negated regex
!^(wp-admin.php$|wp-json/)
matches all URL-paths except/wp-admin.php
(exactly) and anything that starts/wp-json/
. Note that the URL-path matched by theRewriteRule
pattern does not itself start with a slash.Note that this redirects all requests (bar the stated exceptions) to the document root at
my-api-example.com
, as per your example. If you want to preserve the requested URL-path then change the substitution string (2nd argument to theRewriteRule
directive) like so:Note that this is a 302 (temporary) redirect. If this is intended to be permanent then change to a 301, but only once you have confirmed that this works as intended. 301s are cached persistently by the browser so can make testing problematic.
HOWEVER, I suspect you will need to make more exceptions for the "admin" page to be accessible. What about all the static assets (images, CSS, JS, etc.)? I would refrain from excluding any request that simply maps to a physical file since this won’t necessarily redirect requests that perhaps should be redirected.
To make additional exceptions for known directory locations then include additional conditions on the rule. For example, to make an exception for the
/wp-admin/
directory (and all files/directories within) then:You can of course modify the existing
RewriteRule
pattern, although that can get messy if you have many additional exceptions to add.