Delivering multiple Angular2 apps with a single NGINX server, at different URLs

There are certain situations when you want to statically serve multiple Angular apps on the same server, for example:
* an administration UI (feed by an API) and a wizard/form on/for a marketing site (which works with the same API), or
* a platform which statically hosts Angular forms with different designs at different URLs, or
* a web-based back-office comprising a plethora of Angular-based individual micro-apps
All these situations may sound stupid, but… they’re not. Well, I’m not discussion architecture, but rather opportunity. It is a situation, and you have to use NGINX as a static CDN to deliver, let’s say 3 Angular2 apps.

The problems?
* you want all 3 apps to be on
* you may want all 3 of them in different folders/URLs
* Angular’s routing will not permit you, and you know that
* oh, webpack is building them in a /dist/ folder

There are 2 things that you’ll have to fix: Angular2 routing + NGINX setup for location & root directives.
For Angular2 routing, luckily, developers have thought of solutions, like this and this or even this, since May/June/July of 2016. The solution is to build the app using “base-href” option.

cd app_one && ng build --base-href=/app_one/
cd app_two && ng build --base-href=/app_two/
cd app_three && ng build --base-href=/app_three/

This build option will lead to the situation where the index.html of your app will have a BASE href defined accordingly to the path defined in the command.

<base href=”/app_one/” />

For the NGINX setup, you’ll have to override the default NGINX settings by using the following configuration:

location /app_one/ {
alias /var/www/html/app_one/dist/;
try_files $uri$args $uri$args/ /app_one/index.html;
location /app_two/ {
alias /var/www/html/app_two/dist/;
try_files $uri$args $uri$args/ /app_two/index.html;
location /app_three/ {
alias /var/www/html/app_three/dist/;
try_files $uri$args $uri$args/ /app_three/index.html;

This combination of ng build command and NGINX setup has the following advantages:
* you can access your apps through the configured URLs
* if you get on a Angular route, you can refresh pages without getting a 404

Good luck!

Photo credit: Samuel Zeller via