复杂重定向:本地主机上的HTTP到HTTPS +端口和www的裸域,但localhost除外

时间:2014-08-14 12:19:26

标签: asp.net iis azure web-config rewrite

我正在开发一个ASP.NET网站,该网站托管在Microsoft Azure网站上,并且始终通过HTTPS从三个不同的地址组提供服务:

  1. https://www.example.com/https://www.example.co.uk/,二级和三级域名的www子域名
  2. https://example.azurewebsites.net/,azurewebsites.net的子域名,没有www
  3. https://localhost:44300/,没有www的localhost和自定义端口。
  4. 正如我所看到的,我正在尝试制作两个单独的重定向:

    • 从网站的HTTP版本到HTTPS版本,如果需要,添加正确的端口号(本地主机为44300)。
    • 从域的裸版到www子域,除非在localhost。
    但是,我确实想要在可能的情况下仅重定向用户一次,例如直接从“http://example.com/”到“https://www.example.com/”。

    我正在尝试使用Web.config使IIS执行此操作,以便在不必要时不启动ASP.NET。到目前为止,我已经编写了一个IIS重写模块规则,如果我可以用正确的主机和端口({CANOICAL_HOST}www.example.com等替换localhost:44300变量,该规则可以正常工作。 / p>

    <rule name="Force HTTPS and use canonical host">
      <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
          <add input="{HTTPS}" pattern="OFF" />
          <add input="{HTTP_HOST}" negate="true" pattern="^{CANONICAL_HOST}$" />
        </conditions>
      <action type="Redirect" url="https://{CANONICAL_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
    

    我可以让Azure网站在Web.config的appSettings部分插入一个字符串,例如{CANOICAL_HOST}的适当值,并且可以使用XML转换将Web.config中元素的属性更改为静态字符串,但是无法找到任何方法来正确填写这些变量。

    我是否只是尝试使用重写模块的简单工具做太多事情?我应该从ASP.NET中的Application_BeginRequest中放弃并执行它吗?或者有没有办法让这个解决方案有效?

1 个答案:

答案 0 :(得分:0)

我制作了一个ASP.NET / C#解决方案。基本上是:

private void Application_BeginRequest()
{
    var canonicalAuthority = WebConfigurationManager.AppSettings.Get("CanonicalAuthority")
                                 ?? this.Request.Url.Authority;
    // TODO: Might not work with International Domain Names.
    if (!Request.IsSecureConnection
        || !this.Request.Url.Authority.Equals(canonicalAuthority, StringComparison.OrdinalIgnoreCase))
    {
        string path = "https://" + canonicalAuthority + this.Request.Url.PathAndQuery;
        this.Response.RedirectPermanent(path, false);
        this.CompleteRequest();
    }
}

请注意TODO:我认为国际域名的URL编码可能存在问题,但可以使用Uri.Compare修复。