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:
- Updated package.json to have a line for:
"homepage": "http://subdomain.eknighmusic.com/myApp"
- Updated the Router component to have a basename:
<Router basename={'/myApp'}>
- Confirmed any links within my app are using the react-router-dom Link component (or useNavigate) instead of a direct “href”
- 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 sub-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!