IIS配置URL重写将子域名转为{HTTP_HOST}对应路径的正确语法
原有配置失效原因
- 正则规则
^(\w+)\.(.*)$仅支持匹配纯字母、数字、下划线组成的子域名,无法匹配带横杠等合法字符的子域名 - 未保留原始请求的路径和查询参数,用户访问
https://sub.domain.example/xxx?id=1只会被重写到根路径,丢失后续访问内容 - 跨域名场景下
Rewrite动作默认不生效:如果需要用户地址栏跳转,应该用Redirect动作;如果需要保留子域名地址栏显示,需要先开启IIS的ARR反向代理功能才能使用Rewrite
可用配置参考
场景一:301永久重定向(地址栏显示跳转后的https://domain.example/{子域名}路径,最常用)
<rules> <rule name="SubDomain to Subdirectory Redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <!-- 匹配任意合法格式的子域名,适配所有顶级域后缀 --> <add input="{HTTP_HOST}" pattern="^([a-zA-Z0-9-]+)\..*$" /> <!-- 可选:如果要排除www等不需要跳转的子域名,解开下面的注释 --> <!-- <add input="{C:1}" pattern="^www$" negate="true" /> --> </conditions> <!-- {C:1}为捕获到的子域名,{R:1}为原始请求路径,appendQueryString保留查询参数 --> <action type="Redirect" url="https://domain.example/{C:1}/{R:1}" redirectType="Permanent" appendQueryString="true" /> </rule> </rules>
场景二:地址栏保留子域名显示(反向代理重写)
如果需要用户地址栏仍然显示https://sub.domain.example,但实际返回的是https://domain.example/{子域名}的内容,需要先安装启用IIS的应用程序请求路由(ARR)模块,再使用以下配置:
<rules> <rule name="SubDomain to Subdirectory Rewrite" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^([a-zA-Z0-9-]+)\..*$" /> <!-- 可选:排除不需要跳转的子域名 --> <!-- <add input="{C:1}" pattern="^www$" negate="true" /> --> </conditions> <action type="Rewrite" url="https://domain.example/{C:1}/{R:1}" appendQueryString="true" /> </rule> </rules>
内容的提问来源于stack exchange,提问作者Dogmatic
相关产品推荐
相关产品推荐

