X-Forwarded-Proto tells an application whether the client originally used HTTP or HTTPS when connecting through a reverse proxy. This preserves protocol information that can be lost when the proxy forwards the request to the app. section 27.3.2 section 28.4.2
ASP.NET Core reads this header with ForwardedHeadersMiddleware and updates Request.Scheme and related HttpContext properties. Enable the automatically added middleware with ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, or configure it manually. Place it early, before middleware such as UseHttpsRedirection or UseHsts that depends on the request scheme. section 27.3.2 section 28.4.2
Recognizing an HTTPS request behind a proxy
A request reaching the app as http://localhost with X-Forwarded-Proto: https is treated as though it originally used https://localhost. Consequently, later middleware sees the request as secure instead of redirecting it based only on the proxy-to-app connection. section 27.3.2 section 28.4.2
Listing 27.1 Configuring an app to use forwarded headers in Startup.cs
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.UseForwardedHeaders(new ForwardedHeadersOptions #1
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | #2
ForwardedHeaders.XForwardedProto #2
});
app.UseHttpsRedirection(); #3
app.UseRouting(); #3
app.MapGet("/", () => "Hello world!");
app.Run();
Shows a minimal ASP.NET Core pipeline that enables X-Forwarded-Proto and X-Forwarded-For handling before HTTPS redirection and routing. section 27.3.2
