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

Web Config域名重定向规则问题:仅重定向主域与指定子域

解决IIS URL重定向规则问题

首先得指出你现有规则里的核心问题:{HTTP_HOST} 只匹配请求的主机名(也就是www.maindomain.com这部分),不包含路径,所以你用它来匹配/index.html或者/specificSubdomain/完全不对,这部分得用{URL}或者{REQUEST_URI}这类包含路径的变量来判断。

根据你的需求,我们可以拆成两个独立的规则来实现,逻辑更清晰也更容易维护:

规则1:主域根路径重定向到index.html

这个规则专门处理www.maindomain.com/(根路径)的重定向:

<rule name="Redirect Root to Index" stopProcessing="true">
  <match url="^$" /> <!-- 匹配空路径,也就是根目录 -->
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\.maindomain\.com$" /> <!-- 仅匹配主域主机名 -->
  </conditions>
  <action type="Redirect" url="https://www.maindomain.com/index.html" redirectType="Found" />
</rule>

规则2:specificSubdomain路径重定向到对应index.html

这个规则处理www.maindomain.com/specificSubdomain(带或不带末尾斜杠)的重定向:

<rule name="Redirect Specific Subpath to Index" stopProcessing="true">
  <match url="^specificSubdomain/?$" /> <!-- 匹配带或不带末尾斜杠的specificSubdomain路径 -->
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\.maindomain\.com$" /> <!-- 仅匹配主域主机名 -->
  </conditions>
  <action type="Redirect" url="https://www.maindomain.com/specificSubdomain/index.html" redirectType="Found" />
</rule>

关键说明:

  • match url="^$":^和$是正则的开始和结束标记,匹配空字符串,也就是用户访问根路径的情况。
  • match url="^specificSubdomain/?$":/?表示末尾的斜杠是可选的,不管用户访问/specificSubdomain还是/specificSubdomain/都会触发重定向。
  • stopProcessing="true":确保匹配到规则后不再执行后续的重写/重定向规则,避免冲突。
  • 如果需要永久重定向(利于SEO),可以把redirectType="Found"改成redirectType="Permanent"。

把这两个规则放在Web.config的<system.webServer><rewrite><rules>节点下就可以了,其他路径或子域名不会被这些规则影响,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:02:27