404 when trying to enter a react app route
Solution 1:
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:
- Add a custom 404 page which redirects you to index.html.
- If your hosting solution, c-panel, provides an error page setting for the deployment, provide index.html as the error page.
- 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.
Solution 2:
I think I am a bit late ,But the best solution is to : Use HashRouter instead of BrowserRouter and also add a 404.html to public folder with this source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, user-scalable=0, maximum-scale=1, minimum-scale=1"/>
<title>Your Page Title</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script>
var path = window.location.pathname;
path = path[0] + "#" + path;
var url = window.location.protocol + "//" + window.location.hostname + path;
//document.write("Redirecting To: "+url);
window.location.href=url;
</script>
</body>
</html>
So now, if you visit http://example.com/articles it will automatically redirect to http://example.com/#/articles almost instantly which you won't even notice and render correctly without any 404 error!!!.
Note: This answer is suitable if you are using github, if you are using cpanel use custom 404 page with above source code.