Let’s say you have built your next react app and it works flawlessly in your local environment. Now you build the app and upload to a server. You visit the home page and looks great. You click on a link and things don’t look too good. It seems the server does not know how to handle something like myapp.com/login. How can we fix the React route problem?
First you need to configure the Router itself with a basename prop like this:
<Router basename={process.env.REACT_APP_BASENAME}>
I usually keep configurable items in a .env file. I then have one for development and another one for production. If your react app is served from a subdirectory you can adjust the basename prop accordingly. It’s good if you have test and prod versions of the app.
The second thing you have to do is configure the .htaccess file. If you do not see the file you might have to go to your server and enable ‘show hidden files (dotfiles)‘
Once you have the .htaccess file open for edit, add these lines to it:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Basically what we are saying is that redirect any requests to index.html file and then React takes over from there. If you are serving from a different directory then change RewriteBase accordingly. After these changes your app should work.
