MariINova
MariINova

Reputation: 343

ASP.NET Core 6 Razor Pages redirect no www to www with code 301

Today my site can be accessed with https://wwww.example.com or https://example.com our SEO asked me to do a 301 redirect from pages without www to www the same for http access to https, today the system redirects only using code 307, I believe it's done by setting app.UseHttpsRedirection(); in Program.cs, I didn't find how to do this using ASP.NET Core 6, in my Program.cs is like this:

//builder.Services.Configure<RouteOptions>(options =>
//{
//    options.LowercaseUrls = true;
//    options.LowercaseQueryStrings = true;
//});

builder.Services.AddRazorPages(options =>
{
    options.Conventions.AddPageRoute("/MyControll", "My-Page-Default");
});

builder.Services.AddReCaptcha(builder.Configuration.GetSection("ReCaptcha"));

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseStatusCodePagesWithReExecute("/Erro", "?statusCode={0}");
app.UseHttpsRedirection(); //redirect with code 307?
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

My question is, how can I do redirect without www to www and http to httpS using 301 code (moved permanently) or should I do this url check on each control and force redirect by the control?

Thanks!

Upvotes: 0

Views: 900

Answers (1)

Yossi Sternlicht
Yossi Sternlicht

Reputation: 1030

It seems like you are not the first one to need this and asp net core now has these methods built in. Here is a bare-bone of how to achieve both requests.

using Microsoft.AspNetCore.Rewrite;

var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();

var options = new RewriteOptions();
options.AddRedirectToHttpsPermanent();  // THIS CHANGES IT 301
options.AddRedirectToWwwPermanent();    // THIS CHANGES TO WWW AND 301

app.UseRewriter(options);
app.MapGet("/", () => "Hello World!");

app.Run();

Upvotes: 2

Related Questions