Apache rewrite rules configuration for Angular

To run an Angular single-page application on Apache, you have to configure the necessary rewrite rules to handle rewriting to index.html and also reverse proxying your API requests.

This configuration requires two Apache modules to be installed and activated:

  • mod_rewrite
  • mod_proxy

Rewriting to the index page is required to properly handle the Angular routes without having HTTP 404  errors on the server side.  Indeed,  application routes in a single-page application are supposed to be managed just by the frontend running in the browser.

The first rewrite rule has to handle the exclusion of files and directories. This is required to let Apache serve application assets such as js bundles, css, fonts and so on:

RewriteCond %{REQUEST_URI} !^/api/.*$
RewriteRule ^ - [L]

The first two conditions (RewriteCond directive) match requests looking for files or directories; The third condition excludes all the requests having the api prefix in the URL.

The second rewrite rule contains the rewrite to index.html itself:

RewriteCond %{REQUEST_URI} !^/api/.*$
RewriteRule ^ /index.html [L]

The last rule handles the rewriting and proxying of API requests:

RewriteRule ^/api/(.*)$ http://app-backend:8080/api/$1 [P]

The [P] flag activates the mod_proxy module, which is necessary to proxy the request to another host.

Complete configuration file: