PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 21, 2022

[FIXED] How to redirect root folder as subfolder to site?

 September 21, 2022     api, reactjs, rest, virtualhost, wordpress     No comments   

Issue

I am trying to implement the Wordpress REST API with React. Modern convention seems to be to set an API as a subfolder to a domain, i.e.

https://sitename.com/api/v1

I want to be able to go to 
https://sitename.com/api/v1/wp-admin

And be able to sign into wordpress and have it so the REST api is accessed like:

https://sitename.com/api/v1/wp-json/wp/v2/pages

I have this file structure:

Inside api/ is the wordpress install. If I include the api inside the public folder and point towards the build folder with the virtual host, it works as desired, except for the fact that when I build the React app it clears the Wordpress install and restarts that whole process.

I tried setting the virtual host to the subfolder, but it is still returning a 404.

Edit: To get a simple instance of this running:

yarn create-react-app dir_name
cd dir_name
mkdir api
cd api
wp core download
# Add virtual host
# Generate SSL Cert

Solution

The best I've came up with is attaching a symbolic link to the api/ directory and linking it to the build/ directory.

# Source->Destination
ln -s /var/www/site.com/public/api /var/www/site.com/build/

Depending on your configuration you may have to change api/ group once you do a yarn build for the server to have access for Wordpress (to add plugins for example).

Quick run through:

ln -s /var/www/site.com/api /var/www/site.com/public/
yarn build/
sudo chown -R :www-data build/

Edit: I recently adopted what feels like a better approach that uses the apache virtual host.

First, I segmented my root directory into frontend and a backend directory. Inside frontend is the output from create-react-app. Inside backend is api/wp. I nested Wordpress inside an api directory incase the project were to ever expand and include multiple apis, they would all be grouped in one place.

Here is the directory structure

Inside the backend .htaccess is a redirect to the wordpress install

RewriteEngine On
RewriteBase /api
RewriteCond %{REQUEST_URI} !^/api/wp
RewriteRule (.*) wp/$1 [R=302,L]

Inside wordpress is a blank theme I made that redirects to the react app url, in this case, isma.test.



Answered By - Dan
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing