【问题标题】:redirect subdomains from one domain to another domain's subdomain in iis with url rewrite在 iis 中使用 url 重写将子域从一个域重定向到另一个域的子域
【发布时间】:2018-07-28 01:37:09
【问题描述】:

我想将进入 iis 的子域重定向到 localhost:port 中的子域,我的 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 rewrite rules is iis 做到这一点?


编辑:

对于一个子域有一些解决方案(例如question),但我的问题是更笼统的是将所有子域从一个域重定向到另一个域中的相应子域。

【问题讨论】:

标签: iis url-rewriting .net-core


【解决方案1】:

这是执行您要求的重定向的规则:

<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. &lt;match url=".*" /&gt; 匹配任何 URL。请求的 URL 是否在 example.com 域中在稍后的条件中检查。 match 部分对我们的案例没有用处,因为它使用没有主机名的 URL 部分(在第一个 '/' 之后)。

  2. 条件&lt;add input="{HTTP_HOST}" pattern="^((.+.)?)example.com" /&gt; 匹配xyz.example.comexample.com 等域。如果条件匹配,捕获组{C:1} 将包含xyz. 用于xyz.example.com 和空字符串用于example.com,将进一步使用。

  3. &lt;action type="Redirect" url="http://{C:1}localhost:4000{REQUEST_URI}" appendQueryString="false" /&gt;

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

您应该将此&lt;rewrite&gt; 部分添加到站点web.config 下的&lt;system.webServer&gt;。您也可以从 IIS 配置管理器手动配置它。这是此类配置的屏幕截图:

最后,这是一组演示如何更改 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);
    }
}

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2019-01-12
    • 2023-02-14
    相关资源
    最近更新 更多