Best Ways to Redirect HTTP to HTTPS and non-www to www in ASP.NET Core

Best Ways to Redirect HTTP to HTTPS and non-www to www in ASP.NET Core

This basic tutorial shows you three ways on how you can implement URL Rewrite rules using Microsoft.AspNetCore.Rewrite library.

Adding a Rule using a Class

The last method involves implementing a rule using a class.  Right-click your project, select Add -> New Item… and add a class named RedirectToWwwRule.cs.  Replace the entire class with this code:


sing Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Rewrite;
using System;

namespace URLRewriteSample
{
    public class RedirectToWwwRule : IRule
    {
        public virtual void ApplyRule(RewriteContext context)
        {
            var req = context.HttpContext.Request;
            if (req.Host.Host.Contains("www.domain.com", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            if (req.Host.Value.Contains("www.", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            var wwwHost = new HostString($"www.{req.Host.Value}");
            var newUrl = UriHelper.BuildAbsolute(req.Scheme, wwwHost, req.PathBase, req.Path, req.QueryString);
            var response = context.HttpContext.Response;
            response.StatusCode = 301;
            response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
        }
    }
}

Then add the following code to your Startup.cs file:

var options = new RewriteOptions();
options.AddRedirectToHttps();
options.Rules.Add(new RedirectToWwwRule());
app.UseRewriter(options);

Done, enjoy!

In order to use the Microsoft.AspNetCore.Rewrite library, we’ll need to add it using NuGet. 

Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…  Under Browse, type in Microsoft.AspNetCore.Rewrite, highlight it, check the checkbox next to your project, and click on Install.

If you know nothing about how to use the new URL Rewrite Middleware libraries or need some time to learn it, then you’re in luck.  You can still use the good old URL Rewrite syntax from the web.config file.  Right-click on your project, select Add -> New Item… (Ctrl-Shift-A), highlight Data under ASP.NET Core, and select XML File.  In this example, I will name the file RedirectToWwwRule.xml, click on Add, and add the following markup to the file:

<rewrite>
  <rules>
    <rule name="CanonicalHostNameRule">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^www\.domain\.com$" negate="true" />
      </conditions>
      <action type="Redirect" url="http://www.domain.com/{R:1}” />
    </rule>
  </rules>
</rewrite>

Make sure you replace “domain.com” with your domain name in both the pattern and url.  Highlight the XML file and make sure in the Properties window, you select Copy always in the Copy to Output Directory field.  Now open up the Startup.cs file, add a using Microsoft.AspNetCore.Rewrite; directive at the top and enter the following code in Configure method:

app.UseRewriter(new RewriteOptions()
   .AddIISUrlRewrite(env.ContentRootFileProvider, "RedirectToWwwRule.xml")
   .AddRedirectToHttps()
);

What this does is redirect the non-www version of the URL to the www version and redirect HTTP requests to HTTPS.  You could also have removed the .AddRedirectToHttps() method and included it the URL Rewrite rule in the XML file and that would have worked too.

Thanks!



Thanks, for reading the blog, I hope it helps you. Please share this link on your social media accounts so that others can read our valuable content. Share your queries with our expert team and get Free Expert Advice for Your Business today.


About Writer

Ravinder Singh

Full Stack Developer
I have 12+ years of experience in commercial software development. I write this blog as a kind of knowledge base for myself. When I read about something interesting or learn anything I will write about it. I think when writing about a topic you concentrate more and therefore have better study results. The second reason why I write this blog is, that I love teaching and I hope that people find their way on here and can benefit from my content.

Hire me on Linkedin

My portfolio

Ravinder Singh Full Stack Developer