Nginx 和 Create React App(使用 React Router)完整路由不起作用

nux*_*xer 6 javascript deployment nginx reactjs react-router

我已经被困在这个问题上好几天了,我需要互联网的帮助。

我为我的 React 应用程序创建了一个静态 HTML 登陆页面项目(这两个项目是分开的),我希望使用 Nginx 为这两个项目提供服务。我的登陆页面项目有自己的目录结构和资产,如下所示:

/homepage
--index.html
--contact.html
--about-us.html
  /static
   --css files, imgs, ect
Run Code Online (Sandbox Code Playgroud)

我的 React 应用程序是一个 Create React 应用程序,据我所知,在您运行 npm build 后,它会为您提供一个文件夹,build其中包含正确捆绑的所有项目文件,以便您可以部署它。现在我有两个目录,我需要为网站提供服务,但是我很难使用 Nginx 这样做。

我希望我的登陆页面位于 / 所以www.example.comwww.example.com/contact等将导致我的登陆页面项目,然后是www.example.com/appwww.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/;
    }

}
Run Code Online (Sandbox Code Playgroud)

我可以正确地看到我的 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 如下所示:

/homepage
--index.html
--contact.html
--about-us.html
  /static
   --css files, imgs, ect
Run Code Online (Sandbox Code Playgroud)

小智 6

我目前在项目中使用此功能的方法是在 React 应用程序的文件homepage中添加一个字段package.json

{
  "name": "react-app-name",
  ...dependencies and such

  "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "homepage": "https://example.com/app",
  "proxy": "https://example.com/api"
}
Run Code Online (Sandbox Code Playgroud)

除了组件basename中已有的属性之外,您还需要此属性Router。这应该允许您通过 React Router 渲染这些页面。如果您可以看到example.com/app.


cod*_*sfl 3

网络服务器“提供”文件。当您访问时example.com/app,网络服务器只是显示其中的内容/usr/share/nginx/html/app/index.html,同样,如果您访问example.com/app/login,它会尝试显示其中的内容。/usr/share/nginx/html/app/login/index.html

如果没有看到或不知道如何构建 React 应用程序,就很难知道问题是什么。React,当你构建时,只会在构建目录中创建单个 index.html 以及一堆 javascript。

这就是为什么你可以在你的 React 主页( www.example.com/app )上看到它。但是当您导航到 example.com/app/login 时,您就不能这样做了。因为/app有一个index.html,但/app/login没有。Nginx 期望 /app/login 目录下有一个 .html 文件。

快速解决方案: 大多数人会使用 React Router 来创建多页面 React 应用程序。这允许您在反应应用程序中拥有路由。

即使你只有一个index.html,你也可以使用react-router创建不同的“页面”,这一切都由内置的javascript处理,你不必担心在Nginx中创建一堆路由。只需路由到 React 主应用程序,react-router 将处理其余的事情!