'How to avoid 404 error when reload a page in react?

I have a react app developed with Primer-react template. It has an admin dashboard with several routes in the dashboard side panel. I have setup an Auth route in my index.js and it is working perfectly when I go to each route. But when reload the page, the page says 404 page not found!

I protect "/" path from AuthRoute so that every path starting with "/" is protected (I have routes inside the dashboard like "/usertable", "/users", "/payments" etc) . I'm not sure that the error is happening in here because there are some routes (Outside the dashboard) that should be accessed without Auth like "/Signin".

I assumes that if I could protect exact paths for each route which is inside the dashboard (like exact path="/usertable") instead of protect all "/" paths, the 404 problem will be solved! But when I do that, after logout, I can go back to the dashboard by browser back button which generates another problem. How can I solve this?

index.js

import React from 'react';
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
import { render } from 'react-dom';
import Auth from './auth';
import AppProvider from './components/AppProvider/AppProvider';
import Dashboard from './containers/Dashboard';
import { ForgotPassword, Signin, ResetPassword } from './pages';
import registerServiceWorker from './registerServiceWorker';

const AuthRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => {
    if (Auth.isAuthenticated()) {
      return <Component {...props} />
    }
    else {
      return <Redirect to={{ pathname: '/signin' }} />
    }
  }} />
)

export default render(
  <AppProvider>
    <BrowserRouter>
      <Switch>
        <Route exact path="/forgot" component={ForgotPassword} />
        <Route exact path="/signin" component={Signin} />
        <Route exact path="/reset/:token?" component={ResetPassword} />
        <AuthRoute path="/" component={Dashboard} />
        <Route path="/" component={Dashboard} />
      </Switch>
    </BrowserRouter>
  </AppProvider>
  , document.getElementById('root'));

registerServiceWorker();


Solution 1:[1]

If you are using netlify for deploying, then create a _redirects file in the public folder and add the following line to it.

/*  /index.html  200

Solution 2:[2]

If using Netlify and have a netlify.toml file you can add the following

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

Solution 3:[3]

Solution: Past to nginx conf file...

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.html break;
  }
}

I hope this solutions helps any other.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Justin E. Samuels
Solution 3 Safaetul Ahasan Piyas