Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 when trying to enter a react app route

I just deployed my react app build on c-panel. The app includes different routes and everytime I try to get to one of them I get 404 Not found. For example if I try to get to http://example.com/ it will enter the website, and if I'll press on a button which links me tohttp://example.com/articles it will work. But If I'll try to get http://example.com/articles from a link that I shared or just typing this address I'll get 404 Not found. This is not happening when I'm running the develope mode on localhost.

I changed the homepage url - "homepage": "http://example.com", in package.json and it did not effect.

My app root is wrapped with <Router>

function App() {
  return (
    <Provider store={store}>
      <Router>
        <React.Fragment>
          <CssBaseline />
          <Header title="exampletitle" />
          <MobileHeader />
          <Main />
          <BottomNavbar />
        </React.Fragment>
      </Router>
    </Provider>
  );
}

And this is Main.js component which is maneuvered by the routes.

function Main(props) {
  return (
    <div>
      <Switch>
        <Route exact path="/" component={Homepage} />
        <Route exact path="/about" component={About} />
        <Route exact path="/signup" component={Registerpage} />
        <Route exact path="/ap" component={Adminpage} />
        <Route exact path="/signin" component={SignIn} />
        <Route exact path="/userpanel" component={UserPanelPage} />
        <Route path="/article/:category" component={Articlepage} />
        <Route path="/articlepage/:id" component={ReadArticlePage} />
      </Switch>
    </div>
  );
}

Can someone give me a clue how to make those pages load when I enter them directly by their link?

like image 565
SahiBalata Avatar asked Mar 02 '23 10:03

SahiBalata


1 Answers

If your application is working for all the routes when you navigate using <Link> and history.push but throwing 404 Not Found when you type a URL other than http://example.com, say http://example.com/articles, directly in your browser, you need to:

Teach your server to handle 404s by redirecting to the index.html page.

You can do this in one of the following ways:

  1. Add a custom 404 page which redirects you to index.html.
  2. If your hosting solution, c-panel, provides an error page setting for the deployment, provide index.html as the error page.
  3. Use HashRouter from react-router. Check HashRouter Solution and What's HashRouter.

Also, check notes-on-client-side-routing and How to deploy on cPanel.

like image 151
Ajeet Shah Avatar answered Mar 05 '23 17:03

Ajeet Shah