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

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

问题描述

我将 react.js 应用程序上传到服务器.我正在使用 nginx 服务器.应用程序运行良好.但是当我去其他页面&刷新,网站不工作.它显示 404 Not found 错误.

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.

我该如何解决这个问题.

How can I solve this.

谢谢.

推荐答案

当你的 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 发送回浏览器.(参见 https://serverfault.com/questions/329592/how-does-try-files-工作了解更多详情)

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)

这篇关于react.js 应用程序显示 404 在 nginx 服务器中找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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