在访问主页 URL 之前访问的任何 URL 都返回 404

404 returned on any URL accessed before accessing the home URL

我正在为我的应用程序使用 react-router,当我在服务器上部署它时,我注意到如果我在打开主页 URL 之前请求任何 URL,它将 return 404. 然后访问家URL后,所有其他URL都可以正常工作!

index.tsx:

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
  ,
  document.getElementById('root') as HTMLElement
);

App.tsx:

public render()
  {
    return(
        <div className="App">
            <div className="row margin-auto">
                <Header/>
                <Main/>
            </div>
        </div>
    )
  }

Main.tsx:

public render()
    {
        return (
            <div id="main" className="col col-9-and-half no-padding-h vh-100">
                <div className="container-fluid no-padding-h">
                    <main>
                        <Switch>
                            <Route path='/home' component={Home} />
                            <Route exact={true} path='/' component={Home} />
                            <Route path="/matches" component={Matches} />
                            <Route path='/login' component={Login} />
                            <Route path='/sign-up' component={SignUp} />
                            <Route path='/contact-us' component={ContactUs} />
                        </Switch>
                    </main>
                </div>
            </div>
        )
    }

例如,当我尝试打开 www.mywebsite.com/sign-up 时它将 return 404,但是如果我先打开 www.mywebsite.com 然后尝试访问 www.mywebsite.com/sign-up 它将正常工作。

您的服务器似乎没有重定向设置。要使单页 JavaScript 应用程序正常工作,您必须确保您的服务器为您的 index.html 所有路径提供服务。

需要注意的一件事是您必须在 react-router 内管理 404 处理。这可以通过在路由定义的末尾添加不带 path 属性的 <Route /> 来实现。重要的是它在最后,以便在显示 404

之前耗尽所有路由可能性
<Switch>
  <Route path='/home' component={Home} />
  <Route exact={true} path='/' component={Home} />
  <Route path="/matches" component={Matches} />
  <Route path='/login' component={Login} />
  <Route path='/sign-up' component={SignUp} />
  <Route path='/contact-us' component={ContactUs} />
  <Route component={NotFound} />
</Switch>

谢谢 Seth & William Chou 指导我找到答案,我做了以下 htaccess 配置来处理请求,现在一切似乎都工作正常:

<ifModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . /index.html [L]
</ifModule>