Web.config Rewrite

January 18, 2017 - Søren Alsbjerg Hørup

Rewrite rules allow for rewriting an URL to another URI, e.g. accessing / can be rewritten as if the browser had access /abc. This is done on the server side, no 301 redirect is issued back to the client. This allows for prettier URLs.

A web project I am working on consist of a C# Web API 2.0 backend with a Javascript frontend. I wanted to keep all frontend stuff in the /Frontend folder while API stuff in the /Backend folder.

Looking from the perspective of the browser, I wanted that GET /api would rewrite everything to the C# Web API 2.0 backend, while GET / would rewrite everything to the /Frontend folder.

So when requesting e.g. /index.html, the server would rewrite the URL (behind the scenes) to /Frontend/index.html. Nice seperation IMO. This can be done from the Web.config file by writing two rules:

The first rule rewrites /api to /api and stops processing of further requests. This is needed such that the second rule is not processed.

The second rule rewrites /anything to /Frontend/anything, making it possible for me to save my frontend stuff inside the Frontend folder. Very nice indeed.