A couple things to consider when implementing HTTP to HTTPS redirect for an ASP.NET Core application running in Web App on Linux - Azure App Service.
-Since you are using the .NET Core server to process requests, configuring a redirect rule in .htaccess won't work the way it does with sites that are closely coupled with Apache. What you can do instead is implement the redirect in code, using ASP.NET Core Middleware to handle the request and response.
-SSL is offloaded to port 80 from the ARR / front end servers, so using a method such as AddRedirectToHttps() won't work because the request will end up in an infinite redirect loop since it the request on the worker instance will always be on port 80. The way around this is to check for the presence of an X-ARR-SSL header, which indicates that the originating request on the ARR front end was sent over SSL and if this header is not present, redirect to https://url .
Here is a basic example of how to implement this redirect via middleware:
1. Create a Middleware class that contains the logic to redirect the request:
{
public class RedirectToHttpsArrMiddleware
{
private readonly RequestDelegate _next;
{
_next = next;
}
{
//check for the
if (context.Request.IsHttps || context.Request.Headers.ContainsKey("X-ARR-SSL"))
{
//If the X-ARR-SSL request header is present, no need to redirect
context.Request.Scheme = "https";
}
else
{
//redirect to https://url
var request = context.Request;
var newUrl = $"https://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
context.Response.Redirect(newUrl, true);
}
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}
{
public static class RedirectToHttpsArrMiddlewareExtensions
{
public static IApplicationBuilder UseRedirectToHttpsArr(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RedirectToHttpsArrMiddleware>();
}
}
}
3. In the Configure method of the Startup class (in Startup.cs), invoke the Middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRedirectToHttpsArr();
app.Run(async (context) =>
{
await context.Response.WriteAsync(
$"Hello world");
});
}
Further information about using ASP.NET Core Middleware is found at the following link:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware