Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core URL Rewriting

I am trying to redirect my website from www to non-www rules as well as http to https (https://example.com) in the middleware. I used to make those redirection change in the web.config such as:

 <rewrite>
  <rules>
    <clear />
    <rule name="Redirect to https" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
    </rule>
    <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" 
            stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_HOST}" pattern="^example.com$" />
        </conditions>
        <action type="Redirect" url="https://www.example.com/{R:0}" />
    </rule>

I am new to asp.net core and would like to know how can i make those redirection in my middleware? I read this article: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting but it didn't help me to force redirect my www to non-www.

like image 864
Huby03 Avatar asked Apr 14 '17 14:04

Huby03


People also ask

What is URL rewriting in asp net core?

In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.

How do I redirect to another page in net core?

You can use any of the following methods to return a RedirectResult: Redirect – Http Status Code 302 Found (temporarily moved to the URL provided in the location header) RedirectPermanent – Http Status Code 301 Moved Permanently. RedirectPermanentPreserveMethod – Http Status Code 308 Permanent Redirect.


1 Answers

Install the following NuGet package:

Microsoft.AspNetCore.Rewrite

Add the following line:

app.UseCustomRewriter();

within:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

Before calling .UseMvc method.

And add the following extensions class to your project:

public static class ApplicationBuilderExtensions
{
    public static IApplicationBuilder UseCustomRewriter(this IApplicationBuilder app)
    {
        var options = new RewriteOptions()
            .AddRedirectToHttpsPermanent()
            .AddPermanentRedirect("(.*)/$", "$1");

        return app.UseRewriter(options);
    }
}

Within RewriteOptions you can provide your rewrite configuration.

Hoops this will help you out.

Best regards, Colin

like image 77
Colin Raaijmakers Avatar answered Oct 03 '22 12:10

Colin Raaijmakers