IIS URL Rewrite:将QueryString参数转换为子域名
解决QueryString转子域名的URL重写问题
你的需求是把带subdomain参数的URL转换为子域名形式,比如https://mysite.example/?subdomain=test&user=10042转为https://test.mysite.example/?user=10042,原规则存在语法和逻辑问题,调整后的有效规则如下:
情况1:地址栏同步显示子域名(重定向)
如果需要用户浏览器地址栏更新为子域名URL,使用Redirect动作:
<rule name="QS to Subdomain Redirect" stopProcessing="true"> <match url=".*" /> <conditions trackAllCaptures="true"> <!-- 匹配QueryString中任意位置的subdomain参数 --> <add input="{QUERY_STRING}" pattern="(^|&)subdomain=([a-z0-9]+)(&|$)" /> <!-- 限制仅对主域名触发,避免循环重定向 --> <add input="{HTTP_HOST}" pattern="^mysite\.example$" /> </conditions> <!-- 拼接子域名+原路径,关闭自动追加QueryString --> <action type="Redirect" url="https://{C:2}.mysite.example/{R:0}" appendQueryString="false" /> <!-- 移除subdomain参数,保留其他QueryString内容 --> <serverVariables> <set name="QUERY_STRING" value="{C:1}{C:3}" /> </serverVariables> </rule>
情况2:服务器内部重写(地址栏不变)
如果仅需服务器内部处理,地址栏仍显示原URL,使用Rewrite动作:
<rule name="QS to Subdomain Rewrite" stopProcessing="true"> <match url=".*" /> <conditions trackAllCaptures="true"> <add input="{QUERY_STRING}" pattern="(^|&)subdomain=([a-z0-9]+)(&|$)" /> </conditions> <action type="Rewrite" url="https://{C:2}.mysite.example/{R:0}" appendQueryString="false" /> <serverVariables> <set name="QUERY_STRING" value="{C:1}{C:3}" /> </serverVariables> </rule>
关键修改说明:
- 修复了
<match>标签未闭合的语法错误 - 添加
stopProcessing="true"避免后续规则干扰逻辑 - 优化正则表达式,确保准确捕获任意位置的
subdomain参数,同时不破坏其他QueryString内容 - 重定向场景加入
{HTTP_HOST}条件,防止循环跳转 - 通过
appendQueryString="false"和serverVariables精准移除subdomain参数,保留其他参数
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

