Skip to content →

Prepare Apache for Single Page Application (SPA) with a sub context path

Developers using a Single Page frameworks like Angular often put some extra work on the Operations Team.

  • The dev team is early on told to deploy to sub context path like
  • They develop their SPA and find a way to modify the <base href="/subapp" />
  • If the Ops Team is blessed with a farsighted developer, they receive script files, which adds the sub context depending on the environment. Building if Angular one achives this by ng build --configuration=integration --base-href /sem/translator/. This will instruct the Angular compiler to enrich the html base tag.

Fine, one thinks. It’s not.


SPAs process URL request differently. They rely on the web server (nginx, Apache, NodeJS, IIS, WildFly, etc.) to redirect all URL requests to one and single static index.html page. This is where the javascript will reroute responde with the appropriate resources. Of course, there are static resources, which are fetched directly.

So, what happens if Google Search tries to index our a page of our Angular app? e.g. ? That is not a static resource and merely a virtual route by Angular. The browser, provided it has not visited this page before, would fail to service the user.

Solution Approach with Apache

An unparralled way to get around it, is to instruct the web server to handle this.

For Apache one needs to add or create the .htaccess file. Since rewrite rules are also Apache Directives, one can also place them into the httpd.conf or httpd.include files. On Plesk, one may add them to the Apache directives text areas. That is for both, the http and the https area.

Serve the static files

Make sure the Rewrite Engine is On. All physical and existing folder (-d) and files (-f) are served as they are. That includes all your assets like png or jpg images as well as css files.

RewriteEngine On
RewriteRule ^ - [L]

Serve the virtual routes

For the application to be deployed, it requires to apply the sub context path. If you don’t supply that specific path like ^/subapp to the rule – and simply write^ – other applications served by the same domain will suffer from this misconfiguration. Because ^ alone targets the root and everything else that is served under this domain. In other words, requests to files and folders not physicallly present will return the index.html. Imagine the chaos one could create to other apps.

Finally just append the index.html page or whatever your initial page is called. You find that page in angular.json. If you deploy a service worker for PWA then adapt it in ngsw-config.json, too.

RewriteRule ^/subapp.*$ /subapp/index.html


A word of caution. It’s essential to test the rewrite rules properly. Playing on production serve is no option. However, one wont get around doing so for an Single Page App.

Published in DevOps Server Configuration


Leave a Reply

Your email address will not be published. Required fields are marked *