Fixing 404 error for a React SPA on a subdomain

The problem:

I have WordPress installed on my website’s root domain; I wanted to deploy an unrelated React SPA to a subdomain on the same site. The root of the SPA loaded fine, but if I tried to access any routes deeper than the root, I was being served the 404 from my wordpress page.

What I already did:

I set up the application to be served from a subdirectory according to the React Router guidelines:

  1. Updated package.json to have a line for:
    "homepage": "http://subdomain.eknighmusic.com/myApp"
  2. Updated the Router component to have a basename:
    <Router basename={'/myApp'}>
  3. Confirmed any links within my app are using the react-router-dom Link component (or useNavigate) instead of a direct “href”
  4. Updated my image source to: img src={`${process.env.PUBLIC_URL}/icon.png`}

This had everything working from localhost, serving from localhost:3000/myApp and looking good; but I was still having this 404 error after deploying a build and navigating to a route.

The solution:

The .htaccess file at my primary domain’s root was taking over and redirecting any unknown (to the server) routes to my 404 page.

I needed to add a new .htaccess file (filename: .htaccess) in my application’s directory on the server (I used cPanel to do this, but you could use FTP or anything you normally use to move files to your server) with the following contents:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html [L]

Now I can access http://subdomain.eknighmusic.com/myApp/route without getting a 404 error 🙌