ASP.NET Core 2.0 URL Rewriting

Problem

How to implement URL rewriting in ASP.NET Core.

Solution

In Startup, configure RewriteOptions and middleware for URL rewriting:

Run and browse to /films, you’ll notice a redirect:

URL Rewriting - films
Browse to /actors, you’ll notice a rewrite:

URL Rewriting - actors

Discussion

URL Rewriting is about modifying the request URL based on custom rules in order to decouple the address from the underlying resource. This could be for reasons like security, SEO, user friendly URL and redirect HTTP to HTTPS etc.

When you’re unable to use the rewriting features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, Response Rewrite middleware. It’s performance and feature set won’t match server based rewriting features though.

Rewrite middleware is capable of doing both redirects and rewrites:

Redirect

It’s a client-side operation and works like this:

  1. Client requests a resource e.g. /films
  2. Server responds with status code 301 (Moved Permanently) or 302 (Found) with new Location header, instructing client to request the new location e.g. /movies
  3. Client makes request to new location, which will also be shown in the address bar.

Rewrite

It’s a server-side operation and works like this:

  1. Client requests a resource e.g. /actors
  2. Server will internally map to new location e.g. /stars and return 200 (OK).
    1. Client will not know anything about this internal process and will still see the requested URL in address bar.

Rules

Redirect and Rewrite rules are Regular Expressions, details of which could be found in Useful Links section below.

Custom Rules

You could also create custom rules by creating a class and implementing IRule interface:

Custom rule can be added to RewriteOptions:

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Asp.UrlRewriting

Useful Links

URL Rewriting: https://docs.microsoft.com/en-gb/aspnet/core/fundamentals/url-rewriting

Leave a Reply