简体   繁体   中英

Rewrite adressing location from HTTPS to HTTP

Is it possible to rewrite addressing location from https to http? I'm trying several ways to implement this, but it's always opening the page with https.

I tried to add these rules to 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();
            }
        }
    });

This case isn't working for me. I then tried to use the Rewrite option:

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

Which is implemented in the class like this:

    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;

Update: I forgot to note that I've got cases where I need to filter some URLs, which should go to https and which should not

You can do that in web.config, no need to do that from code. Use rewrite rule: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM