“404 未找到"在 React 网站子文件夹上 [英] "404 Not Found" on React website subfolders

查看:46
本文介绍了“404 未找到"在 React 网站子文件夹上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站位于 https://georgi.karapetrov.top/

源代码:https://github.com/GeorgiKarapetrov/georgi.karapetrov.top

问题

指向不同页面的内部链接有效.我可以点击关于"顶部栏中的按钮和关于页面加载.此外,我被路由到关于"的 URL.页面.

The internal links to the different pages work. I can click on the "About" button in the top bar and the about page loads. In addition, I am routed to the URL for the "About" page.

但是,https://georgi.karapetrov.top/about URL 在直接打开.

However, the https://georgi.karapetrov.top/about URL does not load when opened directly.

其他的也一样.访问任何子文件夹"通过单击按钮工作但返回404"在地址栏中输入 URL 时未找到.

The same is true for the rest. Accessing any "sub-folder" works by clicking a button but returns "404" not found when typing the URL in the address bar.

不幸的是,当我尝试访问子文件夹时,NgingX 错误日志中没有任何内容.我不知道我可以路由到 NginX 级别的子目录位置,因为这些子文件夹实际上并不存在于网站路径中.

Unfortunatelly, nothing appears in the NgingX error log, when I try to access a subfolder. I don't know that I can route to sub-directory locations at the NginX level as these sub-folders don't actually exist on website path.

该网站是一个 React 应用程序.相关代码如下所示:

The website is a React App. The relevant code looks like this:

import React, { Suspense, lazy } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

const { PUBLIC_URL } = 'https://georgi.karapetrov.top/';

const About = lazy(() => import('./pages/About'));

const App = () => (
  <BrowserRouter basename={PUBLIC_URL}>
    <Suspense fallback={<Main />}>
      <Switch>
        <Route exact path="/" component={Index} />
        <Route path="/about" component={About} />
        //etc
        <Route component={NotFound} status={404} />
      </Switch>
    </Suspense>
  </BrowserRouter>
);

export default App;

它在本地主机上开发或提供生产构建时按预期工作,使用 npx serve -s build.部署到 NginX 服务器时它不起作用.

It works as intended when developing or serving a production build on local host, with npx serve -s build. It does not work when deployed to an NginX server.

我该如何解决这个问题?

How can I approach this issue?

推荐答案

我错了,配置是NginX级别的.

I was wrong, the configuration is at the NginX level.

虚拟主机配置服务器"用于读取的块:

The virtual host config "server" block used to read:

server {
        #some config
        location / {
                try_files $uri $uri/ =404;
        }
        #etc
}

改变它解决了问题:

server {
        #some config
        location / {
                try_files $uri $uri/ /index.html;
        }
        error_page 404 =200 /index.html;
        #etc
}

现在所有页面都按预期路由.不存在的页面将发送到自定义 404 页面.

Now all pages are routed as they should. Non-existing pages are sent to the custom 404 page.

附言所有功劳都归功于 Ajeet Shah 的原始答案.

p.s. All the credit is to Ajeet Shah's original answer.

这篇关于“404 未找到"在 React 网站子文件夹上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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