【发布时间】:2020-11-21 00:36:15
【问题描述】:
我已经被这个问题困扰了好几天了,我需要互联网的帮助。
我为我的 React 应用程序创建了一个静态 HTML 登录页面项目(这两个项目是分开的),我希望使用 Nginx 为这两个项目提供服务。我的登录页面项目有自己的目录结构和资产,如下所示:
/homepage
--index.html
--contact.html
--about-us.html
/static
--css files, imgs, ect
我的 React 应用程序是一个 Create React 应用程序,据我了解,在您运行 npm build 后,它会为您提供一个名为 build 的文件夹,其中包含正确捆绑的所有项目文件,以便您可以部署它。现在我有两个目录,其中包含为网站提供服务所需的所有内容,但使用 Nginx 很难做到这一点。
我希望我的登陆页面位于 / 所以 www.example.com 和 www.example.com/contact 等会导致我的登陆页面项目,然后 www.example.com/app 和 www.example.com/app/login 等会导致我的反应项目。
我的 Nginx 配置如下所示:
# redirect to https
server {
listen 80;
server_name _;
return 301 https://$host$request_uri;
}
server{
listen 443 ssl;
ssl_certificate /etc/nginx/certs/localhost.pem;
ssl_certificate_key /etc/nginx/certs/localhost-key.pem;
proxy_cookie_path / "/; HTTPOnly; Secure";
location / {
root /usr/share/nginx/html/homepage/;
try_files $uri.html $uri $uri/ =404;
}
location /app/ {
alias /usr/share/nginx/html/app/;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:8080/;
}
}
我可以正确查看我的 react 应用程序主页,但是当我导航到任何其他页面时,例如 https://localhost/app/test,我会被发送到一个损坏的登录页面的 index.html(所有链接/样式坏了)。因此,链接 https://localhost/app 将我定向到我的 react 应用程序的 index.html,但是当我转到 https://localhost/app/test 时它已损坏,它给了我登录页面损坏的 index.html
如何正确配置 nginx 以在我的登录页面项目旁边为我的 react 应用程序的其他路由提供服务?
编辑:
有关更多信息,我添加了一个事实,即我在我的 react 应用程序中使用 React 路由器,并且我的 index.tsx 看起来像这样:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import { Route, BrowserRouter as Router, Switch } from "react-router-dom";
import Home from "./components/Home";
import Login from "./components/Login/Login";
import Dashboard from "./components/Dashboard";
import SignupPage from "./components/Signup/SignupPage";
import DashNavbar from "./components/DashNavbar";
import PersonCard from "./components/PersonCard/PersonCard";
import AnalyticsSmallCard from "./components/AnalyticsSmallCard";
import Test2 from "./components/Test2";
import Test from "./components/Test";
import PrivateRoute from "./components/PrivateRoute";
import NotesSideBar from "./components/NotesSideBar";
import NotesPage from "./components/NotesPage";
import WarningCard from "./components/WarningCard";
const App = (
<Router basename="/app">
<Switch>
<Route path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/signup" component={SignupPage} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<Route path="/test" component={WarningCard} />
</Switch>
</Router>
);
ReactDOM.render(App, document.getElementById("root"));
serviceWorker.unregister();
【问题讨论】:
标签: javascript reactjs nginx deployment react-router