Skip to content

Commit 8fd1dd0

Browse files
feat: redirect www.essentialcsharp.com to apex domain (#1109)
## Problem \www.essentialcsharp.com\ currently returns a 404 (HTTP) or connection reset (HTTPS) because the Azure Container App doesn't handle the \www\ hostname. ## Solution Adds a **301 permanent redirect** in the production middleware pipeline that strips the \www.\ prefix and redirects to the apex domain (\�ssentialcsharp.com\). ### Key details - **Production only** — inside the \!IsDevelopment()\ block, local dev is unaffected - **After \UseForwardedHeaders\** — so the real \Host\ header is readable behind the ACA ingress proxy - No new dependencies ## Required Azure change (separate) \www.essentialcsharp.com\ must be bound as a custom domain on the Azure Container App so traffic reaches the app at all (Azure will also provision a managed TLS cert).
1 parent 73868a6 commit 8fd1dd0

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

EssentialCSharp.Web/Program.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,17 @@ await context.HttpContext.Response.WriteAsync(
443443
// Configure the HTTP request pipeline.
444444
if (!app.Environment.IsDevelopment())
445445
{
446+
SiteSettings siteSettings = app.Services.GetRequiredService<IOptions<SiteSettings>>().Value;
447+
if (!Uri.TryCreate(siteSettings.BaseUrl, UriKind.Absolute, out Uri? configuredBaseUri))
448+
{
449+
throw new InvalidOperationException($"Invalid {SiteSettings.SectionName}:{nameof(SiteSettings.BaseUrl)} value: '{siteSettings.BaseUrl}'.");
450+
}
451+
string apexHost = configuredBaseUri.Host.StartsWith("www.", StringComparison.OrdinalIgnoreCase)
452+
? configuredBaseUri.Host[4..]
453+
: configuredBaseUri.Host;
454+
string wwwHost = $"www.{apexHost}";
455+
string redirectAuthority = new UriBuilder(configuredBaseUri) { Host = apexHost }.Uri.GetLeftPart(UriPartial.Authority);
456+
446457
app.UseExceptionHandler(exceptionApp =>
447458
{
448459
exceptionApp.Run(async context =>
@@ -506,6 +517,19 @@ await McpJsonRpcResponseWriter.WriteErrorAsync(
506517
app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
507518
.AddDefaultSecurePolicy()
508519
.AddContentSecurityPolicy(csp));
520+
521+
// Redirect configured www host to configured apex host (permanent 301).
522+
// Must be after UseForwardedHeaders so the Host header reflects the real hostname.
523+
app.Use(async (context, next) =>
524+
{
525+
if (string.Equals(context.Request.Host.Host, wwwHost, StringComparison.OrdinalIgnoreCase))
526+
{
527+
string redirectUrl = $"{redirectAuthority}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
528+
context.Response.Redirect(redirectUrl, permanent: true);
529+
return;
530+
}
531+
await next(context);
532+
});
509533
}
510534
else
511535
{

0 commit comments

Comments
 (0)