IISAdministration:如何向未初始化的ConfigCollection添加首个元素?
为IIS初始化URL重写规则集合并添加第一条规则
问题场景
全新安装IIS、ARR和URL重写模块且未做任何修改时,applicationHost.config中仅定义了rewrite相关配置节,并未初始化rules集合:
<configSections> <sectionGroup name="system.webServer"> <sectionGroup name="rewrite"> <section name="globalRules" overrideModeDefault="Deny" allowDefinition="AppHostOnly" /> <section name="rules" overrideModeDefault="Allow" /> <section name="outboundRules" overrideModeDefault="Allow" /> <section name="providers" overrideModeDefault="Allow" /> <section name="rewriteMaps" overrideModeDefault="Allow" /> <section name="allowedServerVariables" overrideModeDefault="Deny" /> </sectionGroup> </sectionGroup> </configSections>
此时不存在web.config,规则必须存储在applicationHost.config中。尝试通过以下命令获取规则集合时,返回未初始化状态:
$rulesSection = Get-IISConfigSection -SectionPath "system.webServer/rewrite/rules" # 执行成功 $rulesCollection = $rulesSection | Get-IISConfigCollection # 返回未初始化的集合
直接使用New-IISConfigCollectionElement添加规则元素会因集合不存在而失败。
解决方案
不需要手动单独初始化集合,直接通过指定配置节路径的方式添加规则,系统会自动完成集合的初始化操作。以下是完整的PowerShell步骤:
- 添加基础规则元素
# 直接向rules配置节添加第一条规则,自动初始化集合 $newRule = Add-IISConfigCollectionElement -ConfigSection "system.webServer/rewrite/rules" -ConfigAttribute @{ name = "我的第一条重写规则" enabled = "True" stopProcessing = "False" }
- 配置规则的匹配条件
# 获取规则的匹配条件集合并设置匹配URL $matchElement = $newRule.GetCollection("match") Set-IISConfigAttributeValue -ConfigElement $matchElement -AttributeName "url" -AttributeValue "^old-url/(.*)$"
- 配置规则的操作
# 获取规则的操作集合并设置重写目标 $actionElement = $newRule.GetCollection("action") Set-IISConfigAttributeValue -ConfigElement $actionElement -AttributeName "type" -AttributeValue "Rewrite" Set-IISConfigAttributeValue -ConfigElement $actionElement -AttributeName "url" -AttributeValue "new-url/{R:1}"
如果偏好先获取集合再操作,也可以先通过GetCollection()触发集合初始化,再添加元素:
$rulesSection = Get-IISConfigSection -SectionPath "system.webServer/rewrite/rules" $rulesCollection = $rulesSection.GetCollection() # 触发集合初始化 # 创建并添加规则元素 $newRule = New-IISConfigCollectionElement -ConfigCollection $rulesCollection -ConfigAttribute @{ name = "我的第一条重写规则" enabled = "True" stopProcessing = "False" } # 后续配置匹配条件和操作步骤同上
内容的提问来源于stack exchange,提问作者phochstr
相关产品推荐
相关产品推荐

