且构网

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

使用Nginx在单个域上运行多个React Apps

更新时间:2023-11-22 17:57:46

我不是React应用程序的专家,但是这里有一些简单的方法.

I'm not an expert with react apps but here's few simple ways to do this.

在这两种情况下,请确保您的应用程序都知道它是从子文件夹提供的,因此您需要为所有请求添加/app1//app2/前缀.

In both of these cases make sure that your application understands that it's served from a subfolder so you need to prefix all of your requests with /app1/ or /app2/.

此示例是提供静态文件的最简单的配置.

This example is just simplest possible config which serves the static files.

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;
  }
}

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

You just need to make sure that the folder name matches the subfolder name in your request.

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

Other way to do this is to match the request after the subfolder with regex and use try_files. This way your root folder path can be anything.

# 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;
  }
}