How to deploy a React app in a subdirectory on a WordPress site

The case here is pretty specific, but maybe somebody will be in the situation like me. I have a WordPress site and I wanted to deploy a React app to include in my portfolio and serve it from a subdirectory.

When deploying a React app in a website subdirectory there are some hurdles to overcome. First of all, WordPress redirects most requests to the main index.php file, so when you’re trying to load the app the server might direct the request there and you will get an error. To resolve this you need to edit the .htaccess file so that the requests are correctly routed. Below is the code that you should add in your access file , before the rewrite conditions of WordPress:

RewriteCond %{REQUEST_URI} ^/subdirectory/.*
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ /subdirectory/index.html [L]

If the request URL will start wit the subdirectory and is not an existing file (RewriteCond rules), the request will be routed to the main index file (RewriteRule). The [L] flag tells the server not to process any more rules – otherwise it will execute the following ones as well.

Secondly, the React Router has a handy “basename” attribute that specifies that base of the URLs.

<Router basename="/subdirectory" >                
  <Route path="/my-account" component={Form} />
 <Route path="/about" component={About} />

If we don’t include the attribute the paths would be relative to the main directory and would break. With the baseame, they will all include the base path.

And that’s pretty much it. With those 2 simple tweaks you can make your React app work from a subdirectory on a WordPress site.

Under the URL you can find a React app that I built.