skip to Main Content

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?

3

Answers


  1. In my project, I configured this line of code in nginx to solve the 404 problem after refreshing the page.

    Hope this works for your project.

    server {
      ...
      location / {
        try_files $uri /index.html
      }
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You can set meta tag "prerender-status-code" on the html page and Prerender will return a 404 to the crawler:

    <meta name="prerender-status-code" content="404">
    

    You can do it on React:

    let meta = document.createElement("meta");
    meta.setAttribute("name", "prerender-status-code");
    meta.setAttribute("content", "404");
    document.getElementsByTagName("head")[0].appendChild(meta);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search