How to use Nginx to service multiple React apps

Tonny
2 min readJan 17, 2019

--

Nginx is ideal for static files

I developed multiple SPAs from admin dashboard, merchant portal to user end, but I only had one server for them. The first idea came to me is using Nginx as a proxy.

One way

Take two React apps as an example, one is /app for users, another is /dashboard for admins. I separated them into two project folders and configured Nginx like this.

location /app {
root /html/app;
try_files $uri =404;
}
location /dashboard {
root /html/dashboard;
try_files $uri =404;
}

But all JS and CSS files were under the static path, so I had to router them to their own project folder.

map $http_referer $webroot {
default "/html";
"~/app" "/html/app";
"~/dashboard" "/html/dashboard";
}
location /static {
root $webroot;
}

It worked but was not simple enough. Tricks things always be a bomb in the future.

Another better way

All files in SPAs are static files, and Nginx is an ideal web server for serving these static files. The only thing we need to do is matching URL's path with the server’s folder perfectly.

So I slightly change the build config in app project and dashboard project,

"build": "PUBLIC_URL=/app react-scripts build && cp -R build path_to_html/app"

These JS/CSS asset files in HTML file will under the new public URL.

<script src=”/app/static/js/1.c9859940.chunk.js”></script><script src=”/app/static/js/main.a1dcca7e.chunk.js”></script>

Now, it’s time to remove those dirty config in Nginx, everything works smoothly.

- html
- app
- static
- js
- dashboard
- static
- js

The config in Nginx will be as simple as this:

server {  listen 80;   root /html;
}

and then add one router in React app.

<Route path="/app" component={HomePage} />

but if you need more routers in React app, Nginx will return 404 when you visit /app/user which does not exist under the folder of /html/app.

<Route path="/app/user" component={UserPage} />

you have to one more config in Nginx. Now it will try file /app/index.html rather than 404

location ~ ^/app/((?!(static|(.*\..*))).)+$ {
try_files /app/index.html =404;
}

Keep it simple!

--

--

Tonny
Tonny

Written by Tonny

Mobile developer@NZ. iOS, Android, React

Responses (2)