使用Nginx在单个域上运行多个React Apps [英] Run multiple React Apps on single domain using Nginx

查看:88
本文介绍了使用Nginx在单个域上运行多个React Apps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以推荐最佳实践nginx配置在单个域上运行多个React应用程序吗?这些应用将从不同的根目录中提供.

Can anyone recommend a best practice nginx config to run multiple React apps on a single domain? The apps will be served out of different root directories.

因此app1和app2在www.domain.com上运行并获得服务:

So app1 and app2 run on www.domain.com and get served as:

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

App1从 /tmp1/app1

App1 serves from /tmp1/app1

App2从 /tmp2/app2

App2 serves from /tmp2/app2

推荐答案

我不是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;
  }
}

这篇关于使用Nginx在单个域上运行多个React Apps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆