React router dom direct URL or refresh results in 404

When using React, we’re writing a SPA and when using the React Router we actually need all pages/URL’s to go through App.tsx and the React Router. If everything is not set up correctly you’ll find when you navigate to a page off of the route and refresh the page, or just try to navigate via a direct URL you may end up with a 404 in production, even though everything worked in dev.

Note: Obviously we do not have an App.tsx when transpiled, but I’ll refer to that page as it makes things more obvious what’s going on.

To be more specific to my situation where I discovered these issues – I’ve created a subdomain (on a folder off of the root) for a React site I’m developing that will hosted from that subdomain.

As stated, all works great using serve or the start script. When deployed to production the root page works fine and links from that page via React Router also work fine but refreshing one of those links or trying to navigate directly to a link off of the root results in a 404. So what’s going on?

This issue is that the web server being used is not routing those relative URL’s via the App.tsx router page now and so the React Router is not actually doing anything, it only works when we route things via the App.tsx code.

To solve this, within your React public folder or the root of where you eventually deploy the React web site to, add a .htaccess file (if one is not already there and if your webserver supports this file). Add the following to that file

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

And that’s it, now the web server will route via our App.tsx (index.html).

See the following references which supplied all this information and thanks to these posts I was able to get my React direct links working

404: React Page Not Found
Simple Steps on how to Deploy or Host your ReactJS App in cPanel
Routing single page application on Apache with .htaccess