When your react.js
app loads, the routes are handled on the frontend by the react-router
. Say for example you are at http://a.com
. Then on the page you navigate to http://a.com/b
. This route change is handled in the browser itself. Now when you refresh or open the url http://a.com/b
in the a new tab, the request goes to your nginx
where the particular route does not exist and hence you get 404.
To avoid this, you need to load the root file(usually index.html) for all non matching routes so that nginx
sends the file and the route is then handled by your react app on the browser. To do this you have to make the below change in your nginx.conf
or sites-enabled
appropiately
location / {
try_files $uri /index.html;
}
This tells nginx
to look for the specified $uri
, if it cannot find one then it send index.html
back to the browser. (See https://serverfault.com/questions/329592/how-does-try-files-work for more details)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…