Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run multiple React Apps on single domain using Nginx

Tags:

nginx

reactjs

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.

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

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

App1 serves from /tmp1/app1

App2 serves from /tmp2/app2

like image 394
evolution Avatar asked Nov 08 '22 19:11

evolution


1 Answers

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

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/.

Option 1:

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.

Option 2:

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;
  }
}
like image 114
onnimonni Avatar answered Jan 01 '23 06:01

onnimonni