Introduction
URL rewriting is a process of modifying current request URL and pointing it to some other URL to complete the request. If you were creating an application that has pages /about-us
and /teams
but later after analyzing the site structure, you got a suggestion to move /teams
page under /about-us
so URL looks like /about-us/teams
. After changing structure of your site, you need to redirect old URL /teams
to new URL /about-us/teams
. This is where URL rewriting is needed.
In this article, I will be discussing different solutions for implementing URL rewriting middleware in ASP.NET Core.
When is URL Rewriting Needed?
There may be various situations where you need URL rewriting in your application. Just an example, if SSL is installed for an application, then it can be accessed using both HTTP and HTTPS protocols. In both protocols, request goes for the same page, but SEO identifies them as separate page. Hence, you need URL rewriting to avoid duplicate tracking of the same page. Some of the scenarios that needs URL rewriting are listed below:
- When content is moved to a new page structure and still needs to catch old URL to new URL
- Switch from HTTP to HTTPS
- Switch the non www version to www or www version to non www version
- When there is a new domain and still want to redirect traffic from old domain to new
- Mapping URL querystrings to more SEO friendly URL
URL Rewrite vs Redirect
In the URL rewrite, client sees different URL in browser and server processed different URL. So, basically what we can say is, URL rewrite modifies the URL into server-side before it is fully processed. And this modified URL is not seen to the user’s browser. User only sees what they have requested.
Redirect is a process of sending a new request on the server. It changes URL in the user’s browser and processes a completely new request to the server. In redirect, the user request one URL, and that URL get redirected to a different URL and make a new request. This redirected new URL is visible to user’s browser.
With redirect you can use different status code also. Below table shows all the available status code for redirect
Different URL Rewriting Middleware
In this section, I will explain different ways of URL rewriting middleware with code example. I am not going to discuss about how to create new project in Visual Studio. If you are not familiar with creating project in Visual Studio then you can follow this tutorial. All the code example I have included in this section is based on Visual Studio 2022 and .NET 7.0.
Intercepting Incoming Request
The easiest way to do URL rewriting is to use of app.Use()
inline middleware in Program.cs
, intercept incoming requests, and rewrite them.
Here is the code that rewrites URL.
app.Use(async (context, next) => {
var url = context.Request.Path.Value;
if (url.Contains("/about")) {
context.Request.Path = "/about-us";
}
await next();
});
This code intercepts all the incoming request and check if an incoming URL have /about
or not. If the condition match, then user will get content of /about-us
.
Here is a code example or URL redirect in a similar approach. In redirection, the difference is, redirection is a new request. So, you have to terminate the request in middleware.
app.Use(async (context, next) => {
var url = context.Request.Path.Value;
if (url.Contains("/introduction")) {
context.Response.Redirect("/about-us");
return;
}
await next();
});
ASP.NET Core Rewrite Middleware Module
ASP.NET Core rewrite Middleware module handles complex rewrite and redirect rules. This has the ability to set rewrite and redirect rules based on regEx. This is the most recommended way to use it.
Below code shows how rewrite and redirect can be done in ASP.NET Core Rewrite Middleware module.
var rewrite = new RewriteOptions()
.AddRewrite("about", "about-us", true);
app.UseRewriter(rewrite);
var rewrite = new RewriteOptions()
.AddRedirect("introduction", "about-us");
app.UseRewriter(rewrite);
And here is the code using regEx to rewrite incoming request.
var rewrite = new RewriteOptions()
.AddRewrite(@"^product?id=(\d+)", "product/$1", true);
app.UseRewriter(rewrite);
var rewrite = new RewriteOptions()
.AddRedirect("about/(.*)", "about-us/$1");
app.UseRewriter(rewrite);
IIS URL Rewrite Module
You can use AddIISUrlRewrite
to use IIS URL Rewrite Module rule set. You have to store all the rules in a separate xml
file and don’t forget to deploy them with your application.
Below code read the UrlRewrite.xml
file from app root folder.
var options = new RewriteOptions()
.AddIISUrlRewrite(app.Environment.ContentRootFileProvider, "UrlRewrite.xml");
app.UseRewriter(options);
And this is how UrlRewrite.xml
is with rules. You can add all your rules in a single file.
<rewrite>
<rules>
<rule name="RedirectWwwToNonWww" stopProcessing="false">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>
<rule name="AboutPage" stopProcessing="true">
<match url="^page/about" />
<action type="Redirect" url="about-us" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
If you have Apache web server then you can use AddApacheModRewrite
instead of AddIISUrlRewrite
. And you can place all your Apache mod_rewrite
rules in a text file.
Summary
In this article, I discussed about different ways of implementing URL rewriting in ASP.NET Core. I also explained the importance of URL rewriting and different status codes that has to be used with URL redirect. I hope you will find this article helpful. If you have any suggestions, then please feel free to ask into the comment section.