In .Net Core 5, How to redirect www to non-www URL?

937 views Asked by At

On a subdomain want to redirect all requests with www to non-www, because of that, using this line of code in the "Start.up", in the "Configure" method like below but it doesn't work.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseRewriter(new RewriteOptions().AddRedirectToNonWww());
            ...
        }
   ...
}

What's wrong with my codes? I don't want to write some extra codes like this, because it seems there is a function to handle it.

1

There are 1 answers

0
ChristP On BEST ANSWER

in .net Core 5 put the follow code inside Strartup.cs Configure function

 app.UseRewriter(new RewriteOptions()
            .AddRedirectToNonWwwPermanent()
            .AddRedirectToHttps()
         );

If you use .net Core 6 put the code inside program.cs