6

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

evolution
  • 4,332
  • 5
  • 29
  • 34

2 Answers2

3

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;
  }
}
Onni Hakala
  • 563
  • 4
  • 18
  • do we need to define root inside `server {` as well? – Sizzling Code Jan 24 '20 at 08:10
  • Neither option 1 or 2 works with a deployed react app. I get `[error] 22#22: *1 open() "/etc/nginx/html/app1" failed (2: No such file or directory)` `try_files` does not work with `root`. – Jeffrey Tillwick Feb 16 '23 at 06:35
  • @JeffreyTillwick You probably already solved this but that error message looks like that you don't have any files in the path "/etc/nginx/html/app1". Can you double check that react files are actually in that folder? – Onni Hakala Feb 26 '23 at 09:53
-2

Place

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

Under

location /app1/ {

noamt
  • 7,397
  • 2
  • 37
  • 59
MarlonFan
  • 1
  • 1