【问题标题】:Run multiple React Apps on single domain using Nginx使用 Nginx 在单个域上运行多个 React 应用程序
【发布时间】:2017-07-23 13:24:20
【问题描述】:

谁能推荐一个最佳实践 nginx 配置来在单个域上运行多个 React 应用程序?这些应用程序将在不同的根目录中提供服务。

所以 app1 和 app2 在 www.domain.com 上运行并作为:

www.domain.com/app1
www.domain.com/app2

App1 从 /tmp1/app1

App2 从 /tmp2/app2

【问题讨论】:

    标签: reactjs nginx


    【解决方案1】:

    我不是 React 应用方面的专家,但这里有一些简单的方法可以做到这一点。

    在这两种情况下,请确保您的应用程序了解它是从子文件夹提供的,因此您需要在所有请求前加上 /app1//app2/

    选项 1:

    这个例子只是提供静态文件的最简单的配置。

    server {
      server_name www.domain.com;
    
      # Serve files for different applications from different paths
    
      # Matched location will automatically search files under /tmp1
      # For example request "GET /app1/index.html" returns file /tmp1/app1/index.html
      location /app1 {
        root /tmp1;
      }
    
      location /app2 {
        root /tmp2;
      }
    }
    

    您只需要确保文件夹名称与您请求中的子文件夹名称匹配即可。

    选项 2:

    执行此操作的其他方法是将子文件夹后的请求与regex 匹配并使用try_files。这样你的根文件夹路径可以是任何东西。

    # Serve files from subfolders using regex
    # This comes with additional bonus of matching all requests to the index.html which is usually prefered for react apps
    server {
      server_name www.domain.com;
    
      # Now your root can be anywhere and it doesn't need to contain folder 'app1'
      location /app1/(.*) {
        root /tmp1/app1;
        try_files $1 index.html;
      }
    
      location /app2/(.*) {
        root /tmp2/app2;
        try_files $1 index.html;
      }
    }
    

    【讨论】:

    • 我们还需要在server { 中定义root 吗?
    【解决方案2】:

    地点

    rewrite ^/app1/(.*)$ /$1 break;

    location /app1/ {

    【讨论】:

    • 请提供解释。
    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 2017-02-10
    • 2021-09-22
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2023-03-25
    • 2020-12-31
    相关资源
    最近更新 更多