Search code examples
reactjshttpnginxhttp-status-code-404

How to give a 404 error if there is no page nginx + react.js


I use nginx + react.js Problem with handling 404 error. This method works try_files $uri /index.html; But if you go to the direct URL or reload the page, the browser will always display a 404 on the existing page

Objective: The site should return a page and a 404 code if the URL does not exist. Is this really possible?


Solution

  • If i understood correctly, you are asking how to create a 404 page, not solving 404 code errors on page refreshes.

    It depends how you use React and which packages.

    If you are using React as Client Side SPA, like commonly with create-react-app, there will be only one input; index.html.

    All of your url requests needs to get be redirected to this index file to avoid 404 errors; inside nginx location block with try_files $uri /index.html code.

    From there on your router takes control and reads URL's; redirects it to your components. So you need to solve this 404 page inside React, not with nginx. (There are ways like manually defining your React routes, but we will go with easier.)

    Not sure what router you are using; react-router-dom is commonly used router and i will give my answer for it.

    NotFoundPage component:

    const NotFoundPage = () => (
        <div>
          <h3>
            404 ERROR NOT FOUND
          </h3>
        </div>
      );
    

    Home component, or wherever you defined router paths.

    <Switch>
      <Route exact path="/"> <Home /> </Route>
      <Route path="/about"> <About /> </Route>
      <Route path="/posts"> <Posts /> </Route>
      <Route path="*"> <NotFoundPage /> </Route>
    </Switch>
    

    If you are not using react-router-dom, please edit your question to show which router you are using.