在Nginx服务器中未显示404的react.js应用程序 [英] react.js application showing 404 not found in nginx server
问题描述
我将react.js应用程序上传到服务器.我正在使用nginx服务器.应用程序运行正常.但是当我转到其他页面&刷新,网站无法正常工作.显示404找不到错误.
I uploaded react.js application to server. I'm using nginx server. Application is working fine. But when I go to other page & refresh, site is not working. It's showing 404 Not found error.
我该如何解决.
谢谢.
推荐答案
react.js
应用加载时,路由由react-router
在前端处理.假设您在http://a.com
.然后在页面上导航至http://a.com/b
.此路由更改是在浏览器本身中处理的.现在,当您刷新或打开新标签中的URL http://a.com/b
时,请求将转到您的nginx
,其中该特定路由不存在,因此您会得到404.
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.
为避免这种情况,您需要为所有不匹配的路由加载根文件(通常为index.html),以便nginx
发送该文件,然后由浏览器上的react应用处理该路由.为此,您必须在nginx.conf
或sites-enabled
中适当地进行以下更改
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;
}
这告诉nginx
查找指定的$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.
这篇关于在Nginx服务器中未显示404的react.js应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!