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.