Category Archives: angular

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:

IIS rewrite rules configuration for Angular

Getting Angular to run smoothly on your IIS web server can be tricky at times. Since Angular 2, pretty URLs have become the norm, replacing the old hash-bang locations.

Of course, you also want to proxy your API requests to your backend, and you want all of that to work without disrupting the requests relative to static assets.

To do that, you need a web.config file with some rewrite rules. Here’s a web.config that I’ve put together after working on a few Angular projects deployed on IIS 7.5+. One to route them all.

Let’s go through it and see how it works. The  SpaRewriteRule rewrites to /index.html any request that:

  • is not asking for a file or a directory
  • is not an API request

The ApiProxyRule rewrites all requests with the /api prefix to another (IIS) site, that will be our backend server. Just remember that, for it to work, you’ll need two IIS modules installed and enabled: Url Rewrite and Application Request Routing.

In the handlers section, we register the IIS static file handler that will serve all the Angular assets we have.

Together with that, a wildcard MIME map is registered so that any file type can be served over. This is handy since the assets can contain lots of different file types (fonts, images, etc.) and we don’t have to specify each of them.