7

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

2 Answers 2

4

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;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

do we need to define root inside server { as well?
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.
@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?
-2

Place

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

Under

location /app1/ {

1 Comment

Please, provide the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.