You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IIS重定向规则修改:将所有子域名流量导向主站

问题描述

我在网站的web.config文件中定义了如下重写规则:

<rule name="RedirectWwwToNonWww" enabled="true" stopProcessing="false">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
  </conditions>
  <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>

该规则可实现如下重定向:

  • 来源:www.example.com/test
  • 目标:example.com/test

当前规则运行正常,但我希望修改规则,使所有子域名流量都重定向到主站,例如:

  • 来源:this.example.com/test
  • 目标:example.com/test
    或者
  • 来源:something.example.com/test
  • 目标:example.com/test

我尝试了如下模式:

<add input="{HTTP_HOST}" pattern="^([^.]+)\.(.*)$" />

该模式能正确处理子域名的情况:

  • 来源:something.example.com/test.html
  • 目标:example.com/test.html
    但访问主域名时会出现错误:
  • 来源:example.com/test.html
  • 目标:com/test.html

请问如何修改规则,使子域名重定向到主站,而主域名本身访问时规则不触发?

解决方案

你可以通过两种方式解决这个问题:

方式一:修改正则表达式,仅匹配带子域名的域名

调整{HTTP_HOST}的匹配正则,确保只捕获包含至少一个子域名的主机名,要求主域名部分至少包含一个点(比如example.com这种结构)。修改后的正则为:

<add input="{HTTP_HOST}" pattern="^[^.]+\.(.+\..+)$" />

这个正则的逻辑是:

  • ^[^.]+:匹配第一个点之前的子域名部分
  • \.:匹配分隔子域名和主域名的点
  • (.+\..+):匹配主域名部分,确保其是xxx.xxx的结构

这样当访问example.com时,整个正则无法匹配,规则不会触发;访问xxx.example.com时,会正确捕获主域名部分example.com。

方式二:添加排除主域名的条件

保留你原来尝试的正则,同时在条件组中添加一个否定条件,明确排除主域名本身:

<rule name="RedirectAllSubdomainsToMain" enabled="true" stopProcessing="false">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{HTTP_HOST}" pattern="^([^.]+)\.(.*)$" />
    <!-- 排除主域名本身 -->
    <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
  </conditions>
  <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>

这种方式更灵活,如果你有多个主域名(比如example.co.uk),只需调整否定条件的正则即可。

完整修改后的规则示例(方式一)

<rule name="RedirectAllSubdomainsToMain" enabled="true" stopProcessing="false">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{HTTP_HOST}" pattern="^[^.]+\.(.+\..+)$" />
  </conditions>
  <action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>

内容的提问来源于stack exchange,提问作者4532066

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:52:39