【问题标题】:Rewrite adressing location from HTTPS to HTTP将寻址位置从 HTTPS 重写为 HTTP
【发布时间】:2018-11-08 17:19:59
【问题描述】:

是否可以将地址位置从 https 重写为 http?我正在尝试几种方法来实现这一点,但它总是用 https 打开页面。

我尝试将这些规则添加到app.Use

    app.Use(async (context, next) =>
    {
        if (context.Request.IsHttps)
        {
            if (context.Request.Path.Value.Contains("https") && !context.Request.Path.Value.Contains(".salesrater.com"))
            {
                var path = context.Request.Path.Value.Replace("https", "http");
                context.Response.Headers[HeaderNames.Location] = path;
                context.Response.Redirect(path);
            }
            else
            {
                await next();
            }
        }
    });

这个案子不适合我。然后我尝试使用重写选项:

    var options = new RewriteOptions();
    options.Add(new ServerRewriteRule(cache, Configuration));
    app.UseRewriter(options);

在类中是这样实现的:

    var request = context.HttpContext.Request;
    var path = $"{request.Scheme}://{mapping.Domain}{request.Path.Value.Replace(mapping.Path, string.Empty)}{request.QueryString}";

    if (path.Contains("https"))
    {
        path = path.Replace("https", "http");
    }

    var response = context.HttpContext.Response;
    response.StatusCode = StatusCodes.Status302Found;
    response.Headers[HeaderNames.Location] = path;
    response.Redirect(path);
    context.Result = RuleResult.EndResponse;

更新:我忘记指出我需要过滤一些 URL 的情况,这些 URL 应该转到 https,哪些不应该

【问题讨论】:

  • 在第一种情况下你告诉它context.Response.Redirect(context.Request.Path.Value);,当然它会回到 HTTPS :) 你还需要使用完整的 URI,路径不包含方案 (HTTPS) .
  • @juunas,是的,没有注意到这一点,只是更新了这篇文章,也对我不起作用,它仍然使用 https 运行网站,而不是重定向到 http :(

标签: c# asp.net-core url-rewriting .net-core middleware


【解决方案1】:

您可以在 web.config 中执行此操作,无需通过代码执行此操作。使用重写规则: https://forums.iis.net/t/1206943.aspx?HTTPS+to+HTTP+redirect+in+web+config

<rule name="Redirect to HTTP" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{R:1}" pattern="^onepage/(.*)$" negate="true" />
    <add input="{HTTPS}" pattern="^ON$" />
  </conditions>
  <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" redirectType="Permanent" />
</rule>

【讨论】:

  • @Vitaliy 是的,应该。
  • 我更新了我的帖子,抱歉之前没有注意到,所以我需要过滤一些 url,应该去 https 而不应该去 https
  • @Vitaliy 所以在这种情况下,您可以设置多个规则并使用:
  • 我应该对它们进行硬编码吗?或者我可以通过代码修改它们,因为所有自定义域都存储在数据库中。我想我需要正则表达式来实现这个,因为在我的情况下,只有子域允许使用 https
  • @Vitaliy 由于 web.config 是 XML 文件,您应该能够从代码中创建和修改规则。但它需要一些挖掘。或者是的,您可以对它们进行硬编码。否则,HTTPS有什么问题?所以你需要使用HTTP?
猜你喜欢
  • 1970-01-01
  • 2012-04-21
  • 2011-03-11
  • 1970-01-01
  • 2014-03-04
  • 2014-11-19
  • 1970-01-01
  • 2012-06-17
  • 2014-07-18
相关资源
最近更新 更多