在IIS中使用URL重写将子域名从一个域名重定向到另一个域名的子域名

3

我想将访问IIS的子域名重定向到本地主机上运行的端口的子域名,我的Dotnet核心应用程序正在运行。


简单地说,我想这样重定向:

xyz.example.com => xyz.localhost:4000

john.example.com => john.localhost:4000

test.example.com => test.localhost:4000

example.com => localhost:4000(没有子域名地址重定向到localhost:4000)


如何使用URL重写规则在IIS中实现此目的?


编辑:

有一些针对一个子域名的解决方案(例如此问题),但我的问题更普遍,要求将一个域中的所有子域名重定向到另一个域中相应的子域名。


可能是 将子域名URL重定向到IIS中的另一个子域名 的重复问题。 - NightOwl888
不,这不是重复的问题,因为你提到的那个问题比我的问题简单得多。我需要动态重写所有子域,而不仅仅是我写的示例。 - Hussein Jahanbakhsh
1个回答

5

这里是你所要求的执行重定向的规则:

<rewrite>
    <rules>
        <rule name="Test Rule" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^((.+.)?)example.com" />
            </conditions>
            <action type="Redirect" url="http://{C:1}localhost:4000{REQUEST_URI}" appendQueryString="false" />
        </rule>
    </rules>
</rewrite>

非常简单:

  1. <match url=".*" /> 匹配任何URL。后面的条件检查请求的URL是否在 example.com 域中。对于我们的情况,match 部分是无用的,因为它处理没有主机名的URL部分(第一个“/”后面的部分)。

  2. 条件 <add input="{HTTP_HOST}" pattern="^((.+.)?)example.com" /> 匹配像 xyz.example.comexample.com 这样的域。如果匹配了条件,捕获组 {C:1} 将对于 xyz.example.com 包含 xyz.,对于 example.com 则为空字符串,这将在后面使用。

  3. <action type="Redirect" url="http://{C:1}localhost:4000{REQUEST_URI}" appendQueryString="false" />

    结果URL被构建为 http://{C:1}localhost:4000{REQUEST_URI}。如上所述,{C:1} 将保持子域名,而 {REQUEST_URI} 包含主机名后的URL部分。我们还将 appendQueryString 设置为 false,因为查询是 {REQUEST_URI} 的一部分。

您应该将此 <rewrite> 部分添加到站点的 web.config 下的 <system.webServer> 中。您也可以通过 IIS 配置管理器手动配置它。下面是这种配置的截图:

enter image description here

最后,这里是一组测试,演示了URL如何被更改:

[TestCase("http://xyz.example.com", "http://xyz.localhost:4000/")]
[TestCase("http://xyz.example.com/some/inner/path", "http://xyz.localhost:4000/some/inner/path")]
[TestCase("http://xyz.example.com/some/inner/path?param1=value1&param2=value2", "http://xyz.localhost:4000/some/inner/path?param1=value1&param2=value2")]
[TestCase("http://example.com", "http://localhost:4000/")]
[TestCase("http://example.com/some/inner/path", "http://localhost:4000/some/inner/path")]
[TestCase("http://example.com/some/inner/path?param1=value1&param2=value2", "http://localhost:4000/some/inner/path?param1=value1&param2=value2")]
public void CheckUrlRedirect(string originalUrl, string expectedRedirectUrl)
{
    using (var httpClient = new HttpClient(new HttpClientHandler {AllowAutoRedirect = false}))
    {
        var response = httpClient.GetAsync(originalUrl).Result;

        Assert.AreEqual(HttpStatusCode.MovedPermanently, response.StatusCode);
        var redirectUrl = response.Headers.Location.ToString();
        Assert.AreEqual(expectedRedirectUrl, redirectUrl);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,