How does the UseHttpsRedirection() middleware determine which port to redirect to, and how do you explicitly configure it when the HTTPS port isn't on the default 443?
Short answer
By default, UseHttpsRedirection() attempts to infer the HTTPS port from Kestrel's own configuration or the ASPNETCORE_HTTPS_PORT environment variable, but in scenarios where the app runs behind a reverse proxy or in a non-standard port setup, this inference can fail or be wrong…
Advertisement
AModel answer
By default, UseHttpsRedirection() attempts to infer the HTTPS port from Kestrel's own configuration or the ASPNETCORE_HTTPS_PORT environment variable, but in scenarios where the app runs behind a reverse proxy or in a non-standard port setup, this inference can fail or be wrong, in which case explicitly configuring HttpsRedirectionOptions.HttpsPort ensures the redirect always points to the correct externally-accessible HTTPS port rather than an internal-only port the client can't actually reach.
builder.Services.AddHttpsRedirection(options => {
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443; // explicit external port, even if Kestrel listens internally on a different port
});Real-world example
An app running behind a reverse proxy that exposes HTTPS externally on the standard 443 while Kestrel itself listens internally on 5001 explicitly configures HttpsPort to 443, ensuring redirected clients are sent to the correct externally-reachable address rather than the internal-only port.
Likely follow-ups
- What redirect status code should be used, and why does 308 differ meaningfully from 301 for this purpose?
- When is HTTPS redirection better handled at the reverse proxy layer instead of within the application?
Related topics