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
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.
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:
Home component, or wherever you defined router paths.
If you are not using react-router-dom, please edit your question to show which router you are using.
You can set meta tag "prerender-status-code" on the html page and Prerender will return a 404 to the crawler:
You can do it on React: