This article explains the concept and implementation of URL rewriting in ASP.NET Core. It covers scenarios where URL rewriting is needed, the difference between URL rewriting and redirection, and provides detailed steps and code examples for implementing URL rewriting using inline middleware, the ASP.NET Core Rewrite Middleware module, and the IIS URL Rewrite Module. 

Pasang Tamang

Pasang Tamang

June 01, 2024

URL rewriting is the process of modifying the URL of an incoming request to point to a different URL without changing the requested resource. For example, if your application initially has pages /about-us and /teams, and you decide to move the /teams page under /about-us to form /about-us/teams, URL rewriting ensures that requests to the old URL /teams are redirected to the new URL /about-us/teams.

When is URL Rewriting Needed?

URL rewriting can be necessary in various situations, including:

  • Content Restructuring: When the structure of your site changes, such as moving /teams to /about-us/teams.
  • Protocol Switching: To redirect from HTTP to HTTPS.
  • Domain Switching: To redirect traffic from an old domain to a new one.
  • SEO Optimization: To create more SEO-friendly URLs by mapping query strings to cleaner URLs.

 

Some common scenarios requiring URL rewriting include:

  • Moving content to a new page structure and maintaining old URL access.
  • Switching from HTTP to HTTPS.
  • Redirecting the non-www version to www or vice versa.
  • Redirecting traffic from an old domain to a new domain.
  • Mapping URL query strings to more SEO-friendly URLs.

 

URL Rewrite vs Redirect

  • URL Rewrite: The client sees one URL in the browser, but the server processes a different URL. The modified URL is processed server-side and is not visible to the user.

  • Redirect: The client is sent a new URL, which is visible in the browser. The server processes a new request to the new URL.

With redirects, you can use different status codes. The table below shows all available status codes for redirects.

 

Implementing URL Rewriting Middleware in ASP.NET Core

1. Inline Middleware in Program.cs

To intercept incoming requests and rewrite URLs inline in Program.cs:

app.Use(async (context, next) => {
    var url = context.Request.Path.Value;
    if (url.Contains("/about")) {
        context.Request.Path = "/about-us";
    }
    await next();
});

 

To implement URL redirection inline in Program.cs:

app.Use(async (context, next) => {
    var url = context.Request.Path.Value;
    if (url.Contains("/introduction")) {
        context.Response.Redirect("/about-us");
        return;
    }
    await next();
});

 

 

2. ASP.NET Core Rewrite Middleware Module

The ASP.NET Core Rewrite Middleware module handles complex rewrite and redirect rules, including regex-based transformations. This is the recommended approach for robust URL rewriting.

To rewrite and redirect URLs using the Rewrite Middleware module:

var rewrite = new RewriteOptions()
    .AddRewrite("about", "about-us", true)
    .AddRedirect("introduction", "about-us");
app.UseRewriter(rewrite);

 

To use regex for URL rewriting:

var rewrite = new RewriteOptions()
    .AddRewrite(@"^product?id=(\d+)", "product/$1", true)
    .AddRedirect("about/(.*)", "about-us/$1");
app.UseRewriter(rewrite);

 

 

3. Integration with IIS URL Rewrite Module

For IIS users, define rewrite rules in an XML file and deploy them with the application:

var options = new RewriteOptions()
    .AddIISUrlRewrite(app.Environment.ContentRootFileProvider, "UrlRewrite.xml");
app.UseRewriter(options);

 

Example UrlRewrite.xml 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>

 

For Apache web server users, use AddApacheModRewrite instead of AddIISUrlRewrite and place all mod_rewrite rules in a text file.

Conclusion

This article discussed various methods of implementing URL rewriting in ASP.NET Core. It covered the importance of URL rewriting and different status codes used with URL redirects. Mastering these techniques helps manage site structure, enhance SEO, and ensure seamless user experiences.

**Further Learning:**

* How to integrate Elasticsearch in ASP.NET core