且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React应用返回500内部服务器错误

更新时间:2022-10-20 16:40:45

直接访问应用程序的路线时,例如通过 https://myapp.com/route/123 Apache尝试将该URL映射到公用文件夹.在这种情况下,它会查找/route/123.html,该地址显然不存在.为了避免这种情况,我们必须告诉Apache将所有请求重定向到我们的index.html,以便我们的应用程序可以对该URL执行一些路由魔术.要告诉Apache将请求重定向到应用程序所在的index.html,我们必须修改.htaccess文件.如果您的应用文件夹中还没有此类文件,则只需创建它即可.

  Options -MultiViewsRewriteEngine开RewriteCond%{REQUEST_FILENAME}!-fRewriteRule ^ index.html [QSA,L] 

有关更多信息,请..>

I have a react app, created using create-react-app.

After I run npm run build, and deploy the app as a static site, everything works except when I refresh the page on a route other than the index, it fails with a 500 internal server error.

Below is the code for my router. Using react-router.

<Router history={browserHistory}>
  <Route path="/">
      <IndexRoute component={Login}/>
      <Route path="/dashboard" component={Dashboard}></Route>
      <Route path="/profile" component={Profile}/>
</Router>

Any help appreciated.

When you’re visiting a route of your app directly, e.g. via https://myapp.com/route/123 Apache tries to map that URL to a file in the public folder. In this case it looks for /route/123.html which obviously doesn’t exist. To avoid that, we have to tell Apache to redirect all requests to our index.html so our app can perform some routing magic for that URL. To tell Apache to redirect requests to index.html where our app lives, we have to modify the .htaccess file. If there is no such file in your app’s folder yet, just create it.

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

for more information check this out.