我正在开发一个ASP.NET网站,该网站托管在Microsoft Azure网站上,并且始终通过HTTPS从三个不同的地址组提供服务:
https://www.example.com/
和https://www.example.co.uk/
,二级和三级域名的www子域名https://example.azurewebsites.net/
,azurewebsites.net的子域名,没有www https://localhost:44300/
,没有www的localhost和自定义端口。正如我所看到的,我正在尝试制作两个单独的重定向:
我正在尝试使用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中放弃并执行它吗?或者有没有办法让这个解决方案有效?
答案 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
修复。