即使在添加 .htaccess 之后,react应用程序中的 Apache 错误 404

IT技术 reactjs .htaccess web-deployment apache2.4
2021-05-24 09:23:04

我有一个生产react应用程序(构建文件夹的内容) /var/www/my_webpage/

这是我的虚拟主机配置

<VirtualHost *:80>

        ServerName www.domain.com
        ServerAlias domain.com
        DocumentRoot /var/www/my_webpage


        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

# redirect all the http requests to https - added automatically by CertBot
        RewriteEngine on
        RewriteCond %{SERVER_NAME} =prudent-solutions.co.in [OR]
        RewriteCond %{SERVER_NAME} =www.prudent-solutions.co.in
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

和我.htaccess在文档根目录中的文件/var/www/my_webpage

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

主页工作正常。但是当我访问 domain.com/some_thing 时,我收到来自Apache的 404 错误
我浏览了许多网站和教程以进行react部署。我无法理解他们是如何简单地添加一个 .htaccess 文件并使他们的网站正常工作以及为什么我没有发生同样的事情。我对 Apache mod_rewrite 完全陌生。

另外,我对设置单独的 express.js 服务器来将所有请求路由到 index.html 文件或使用 HashRouter 而不是 BrowserRouter 不感兴趣。
错误截图

错误截图

我的react-router

import "./App.css";

// Importing react components/Pages ----------------------------------
import Revamp from "./components/Misc/Revamp";
import Navbar from "./Shared/Navbar";
// Importing Route requirements ----------
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <Router>
        <Navbar />
        <Switch>
          <Route component={Revamp} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

我的 manifest.json

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "homepage": ".",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

额外细节

Apache version:
Server version: Apache/2.4.41 (Ubuntu)
Server built:   2020-08-12T19:46:17 
1个回答

您需要教您的服务器在错误 404 时重定向到 index.html

<VirtualHost *:80>

  # ...

  DocumentRoot /var/www/my_webpage

  <Directory "/var/www/my_webpage">
    AllowOverride None # Line 1
    ErrorDocument 404 /index.html # Line 2: Here we set ErrorDocument
    Require all granted
  </Directory>

  # ...

现在,您需要重新启动 apache2 服务器。


或者,.htaccess在项目根目录下的文件中添加以下行(不要忘记AllowOverride ALL在上面显示的第 1 行):

ErrorDocument 404 /index.html