You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.Net Core生产环境中通过Rewrite Middleware将非WWW重定向到WWW

Hey there! Let's break down how to implement that non-WWW to WWW redirect using ASP.NET Core's Rewrite Middleware, and make sure it only activates in production. Here are two reliable approaches:

Option 1: Use the Built-in Canonical Host Rule (Simplest)

ASP.NET Core has a ready-made rule for canonical host redirection, which is perfect for this scenario—it handles all the heavy lifting for you.

In your Program.cs (for .NET 6+ with top-level statements), add this logic after building the app but before other core middleware like routing or static files:

var builder = WebApplication.CreateBuilder(args);

// Add your services here (e.g., AddControllers, AddRazorPages, etc.)
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure error handling first (standard practice)
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

// 👇 Add the rewrite rule ONLY in production
if (app.Environment.IsProduction())
{
    var rewriteOptions = new RewriteOptions()
        // Replace "www.yourdomain.com" with your actual WWW domain
        .AddCanonicalHostRewriteRule("www.yourdomain.com", permanent: true);

    app.UseRewriter(rewriteOptions);
}

// Continue with other middleware setup
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Key Notes for This Option:

  • permanent: true sends a 301 Permanent Redirect, which is ideal for SEO (tells search engines to update their indexes to the WWW domain).
  • The rule automatically preserves the request path, query strings, and scheme (HTTP/HTTPS) when redirecting.
  • Make sure UseRewriter comes before middleware that processes the request (like UseStaticFiles or UseRouting) so the redirect happens early.

Option 2: Custom Rewrite Rule (For Flexibility)

If you need more control (e.g., handling multiple non-WWW domains, port-specific logic), you can create a custom rule instead:

if (app.Environment.IsProduction())
{
    app.UseRewriter(new RewriteOptions().Add(context =>
    {
        var request = context.HttpContext.Request;
        var currentHost = request.Host;

        // Skip if the host already starts with www.
        if (currentHost.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        // Build the new WWW host (preserve port if needed)
        var newHost = new HostString($"www.{currentHost.Host}", currentHost.Port);
        // Construct the full redirect URL
        var redirectUrl = UriHelper.BuildAbsolute(
            request.Scheme,
            newHost,
            request.PathBase,
            request.Path,
            request.QueryString);

        // Send 301 redirect and stop processing further middleware
        context.HttpContext.Response.Redirect(redirectUrl, permanent: true);
        context.Result = RuleResult.EndResponse;
    }));
}

Why This Might Be Useful:

  • You can add additional checks (e.g., exclude specific subdomains if needed).
  • Full control over how the redirect URL is constructed.

Critical Reminders:

  • Environment Check: Always wrap the rule in app.Environment.IsProduction() so it doesn't interfere with local development (you don't want to redirect localhost to www.localhost!).
  • HTTPS: If your production site uses HTTPS, ensure UseHttpsRedirection is in place (it should be by default in new projects) to redirect HTTP to HTTPS first, then handle the WWW redirect.
  • Testing: Before deploying, verify the redirect works using tools like curl or browser dev tools to confirm the 301 status code and correct target URL.

内容的提问来源于stack exchange,提问作者Miguel Moura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:19:26