Serving multi page Angular2+ apps with nginx server from respective sub-directories

Serving multi page Angular2+ apps with nginx server from respective sub-directories

If you are working with javascript libraries like Angular, React, Ember etc. there are certain situations where you go the MPA or Multi Page Application architechture way. With a MPA, you have each page in a MPA as a SPA or Single Page Application that is either built with either of the javascript libraries. But you want to host and serve these SPAs using a single NGINX server because you want to host all the SPAs on a single server.

The Problem

  • You want all the SPAs to behave like a single application. i.e. you want all the apps to be on a single domain.
  • You want all the SPAs to be accessible through different URLs on the same domain.
  • Their respective routing won’t allow you to do that.

The solution

For this article let’s say we have 3 SPAs in Angular 2+. And all the SPAs are hosted like this:

 /var/www/html/app/
  app_a/
   dist/
    index.html
    ...
   ...
  app_b/
   dist/
    index.html
    ...
   ...
  app_c/
   dist/
    index.html
    ...
   ...

But we want all the SPAs to be accessible like this:

 http://www.app.com
  http://www.app.com/app_a
  http://www.app.com/app_b
  http://www.app.com/app_c

For this we need to fix 2 things.

1. Angular2+ routing: For this we update the ng build build using --base-href option.

 ng build --base-href=/app_a/
 ng build --base-href=/app_b/
 ng build --base-href=/app_c/

2. NGINX setup: For this we override the default NGINX settings like this:

 server {
  listen 80;
  server_name app.com;
  charset utf-8;
  ssl off;
  root  /var/www/html/app/;
  
  location /app_a {
   alias /var/www/html/app/app_a/dist/;
   try_files $uri$args $uri$args/ /app_a/index.html;
  }

  location /app_b {
   alias /var/www/html/app/app_b/dist/;
   try_files $uri$args $uri$args/ /app_b/index.html;
  }

  location /app_c {
   alias /var/www/html/app/app_c/dist/;
   try_files $uri$args $uri$args/ /app_c/index.html;
  }
}

The Conclusion

The combination of Angular2+ routing and NGINX allows us to:

  • Access the SPAs through configured URLs.
  • For an angular SPA, if we refresh page, we don’t get a 404 error.