跳转 https 用的是 asp.net core 内置的 url 重写规则
var rewriteOptions = new RewriteOptions()
.AddRedirectToHttpsPermanent();
发现通过 IP 地址访问也会强制跳转 https
curl -i http://192.168.107.240/metrics
HTTP/1.1 301 Moved Permanently
Date: Sat, 18 Jan 2020 03:23:06 GMT
Server: Kestrel
Content-Length: 0
Location: https://192.168.107.240/metrics
请问如何解决?
AddRedirect 自己搞個rule,非ip才 to https
通过下面的 url 重写规则 RedirectToHttpsRule 实现了,ASP.NET Core 内置的 https 跳转组件的判断逻辑是只要 X-Forwarded-Proto 不是 https 就跳转
,我觉得更合理的判断逻辑是只有 X-Forwarded-Proto 为 http 时才跳转
,这样如果没有设置 X-Forwarded-Proto 就不会跳转。
RedirectToHttpsRule.cs
namespace Cnblogs.Web.Rewrite
{
public class RedirectToHttpsRule : IRule
{
private const string HEADER_HAME = "X-Forwarded-Proto";
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
if (request.Headers.TryGetValue(HEADER_HAME, out var forwardedProto))
{
if (forwardedProto.ToString() == "http")
{
var isHttpGet = request.Method.Equals("get", StringComparison.OrdinalIgnoreCase);
var statusCode = isHttpGet ? StatusCodes.Status301MovedPermanently : StatusCodes.Status307TemporaryRedirect;
var host = context.HttpContext.Request.Host;
var newUrl = new StringBuilder()
.Append("https://")
.Append(host)
.Append(request.PathBase)
.Append(request.Path)
.Append(request.QueryString);
var response = context.HttpContext.Response;
response.StatusCode = statusCode;
response.Headers[HeaderNames.Location] = newUrl.ToString();
context.Result = RuleResult.EndResponse;
}
}
}
}
}
RewriteOptionsExtensions.cs
namespace Cnblogs.Web.Rewrite
{
public static class RewriteOptionsExtensions
{
public static RewriteOptions AddCnblogsRedirectToHttps(this RewriteOptions options)
{
options.Rules.Add(new RedirectToHttpsRule());
return options;
}
}
}
HttpsRedirectionBuilderExtensions.cs
namespace Microsoft.AspNetCore.Builder
{
public static class HttpsRedirectionBuilderExtensions
{
public static IApplicationBuilder UseCnblogsHttpsRedirection(this IApplicationBuilder app)
{
app.UseRewriter(new RewriteOptions().AddCnblogsRedirectToHttps());
return app;
}
}
}