【问题标题】:Complex redirect: HTTP to HTTPS + port on localhost and naked domain to www, except on localhost复杂的重定向:HTTP 到 HTTPS + localhost 上的端口和裸域到 www,除了 localhost
【发布时间】:2014-08-14 12:19:26
【问题描述】:

我正在开发一个托管在 Microsoft Azure 网站上的 ASP.NET 网站,该网站将从三个不同的地址组提供服务,始终通过 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 的本地主机,来自自定义端口。

正如我所见,我正在尝试进行两个单独的重定向:

  • 从站点的 HTTP 版本到 HTTPS 版本,如果需要,添加正确的端口号(本地主机为 44300)。
  • 从裸版域到 www 子域,除非在本地主机上。

但是,如果可能,我只想将用户重定向一次,例如直接从'http://example.com/'到'https://www.example.com/'。

我正在尝试让 IIS 使用 Web.config 执行此操作,以免在不必要时启动 ASP.NET。到目前为止,我已经编写了一个 IIS 重写模块规则,如果我可以将 {CANOICAL_HOST} 变量替换为正确的主机和端口(@98​​7654328@、localhost:44300 等),它就可以工作:

<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 网站将一个字符串(例如 {CANOICAL_HOST} 的适当值)插入 Web.config 的 appSettings 部分,并且可以使用 XML 转换将 Web.config 中元素的属性更改为静态字符串,但不能真的找不到任何方法来正确填写这些变量。

我只是想用重写模块这个简单的工具做太多事情吗?我应该放弃并从 ASP.NET 中的 Application_BeginRequest 开始吗?或者有没有办法让这个解决方案发挥作用?

【问题讨论】:

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


    【解决方案1】:

    我做了一个 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 来解决。

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 2019-06-14
      • 2016-11-08
      • 2018-12-10
      • 2021-07-30
      • 2014-05-07
      • 2020-12-28
      • 2013-06-29
      • 1970-01-01
      相关资源
      最近更新 更多