在Nginx服务器中未显示404的react.js应用程序 [英] react.js application showing 404 not found in nginx server

查看:243
本文介绍了在Nginx服务器中未显示404的react.js应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将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.confsites-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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆