HTTPS redirection answers an HTTP request with a redirect to the same URL over HTTPS, preventing intercepted traffic from being read or modified. In ASP.NET Core, app.UseHttpsRedirection() commonly produces a temporary 307 response with a Location header containing the HTTPS address. section 9.3
Enable redirection
Add app.UseHttpsRedirection() to the application pipeline. Test it by opening http://localhost:<port>/swagger/index.html and checking the Network tab for a 307 response and HTTPS Location header. section 9.3
Choose the deployment strategy deliberately:
- Use temporary redirects during development, avoiding browser caching problems caused by permanent redirects. section 9.3
- In production, avoid exposing an HTTP port behind a proxy such as Istio, or permanently redirect HTTP requests to HTTPS. section 9.3
- Enable HSTS in production so browsers remember that the site should use HTTPS. section 9.3
Listing 9.3 Enabling HSTS in production
var app = builder.Build();
if (app.Environment.IsProduction()) #1
{
app.UseHsts(); #2
}
Shows conditional production-only HSTS middleware configuration. section 9.3
Listing 9.4 Configuring HSTS
builder.Services.AddHsts(options => #1
{
options.Preload = true; #2
options.IncludeSubDomains = true; #3
options.MaxAge = #4
DateTime.UtcNow.AddYears(1) - DateTime.UtcNow; #5
options.ExcludedHosts.Add("test.manningcatalog.net"); #6
});
var app = builder.Build();
Shows HSTS options for preload, subdomains, duration, and excluded hosts. section 9.3
