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

如何用PowerShell在Azure应用网关单个规则集中创建多个重写规则

解决Azure应用网关单规则集添加多重写规则问题

原代码问题分析

  • 循环内重复执行Add-AzApplicationGatewayRewriteRuleSet,每次仅传入单个规则,无法批量添加到同一规则集
  • 错误使用$rule.ProvisioningState作为规则参数,应直接传入创建好的$rule对象
  • 循环内频繁调用Set-AzApplicationGateway,多次触发网关配置更新,易引发冲突且效率低下

修正后的实现代码

# 获取应用网关配置
$appGW = Get-AzApplicationGateway -Name "A3D0DVAPIAGW01ET" -ResourceGroupName "A3D0DVAPIRSG01T"

# 定义重写规则配置
$json = @"
{
"Rules": 
    [
        {
            "Name": "DDO",
            "Path": "/etp/{var_request_uri}",
            "Pattern": "/ddo/*"
        },
         {
            "Name": "AM",
            "Path": "/efp/{var_request_uri}",
            "Pattern": "fsamtpf/*"
        }
    ]
}
"@
$rewriteRulesConfig = ConvertFrom-Json $json

# 批量创建重写规则对象
$rewriteRules = @()
foreach ($ruleConfig in $rewriteRulesConfig.Rules) {
    $urlConfig = New-AzApplicationGatewayRewriteRuleUrlConfiguration -ModifiedPath $ruleConfig.Path
    $actionSet = New-AzApplicationGatewayRewriteRuleActionSet -UrlConfiguration $urlConfig
    $condition = New-AzApplicationGatewayRewriteRuleCondition -Variable "var_request_uri" -Pattern $ruleConfig.Pattern -IgnoreCase
    $rewriteRule = New-AzApplicationGatewayRewriteRule -Name $ruleConfig.Name -ActionSet $actionSet -Condition $condition
    $rewriteRules += $rewriteRule
}

# 检查目标规则集是否已存在
$existingRuleSet = $appGW.RewriteRuleSets | Where-Object { $_.Name -eq "BWL_Rewrite" }

if ($existingRuleSet) {
    # 若规则集已存在,添加新规则到现有规则集
    $updatedRuleSet = Add-AzApplicationGatewayRewriteRuleSet -ApplicationGateway $appGW `
                                                             -Name $existingRuleSet.Name `
                                                             -RewriteRule $rewriteRules
    $appGW = $updatedRuleSet
} else {
    # 若规则集不存在,创建新规则集并添加所有规则
    $appGW = Add-AzApplicationGatewayRewriteRuleSet -ApplicationGateway $appGW `
                                                     -Name "BWL_Rewrite" `
                                                     -RewriteRule $rewriteRules
}

# 一次性更新应用网关配置
$appGW | Set-AzApplicationGateway

关键说明

  • 先批量创建所有RewriteRule对象,再统一添加到规则集,确保同一规则集包含多个规则
  • 先检查规则集是否存在,避免重复创建或覆盖现有规则
  • 仅在所有规则配置完成后执行一次Set-AzApplicationGateway,减少网关更新次数,提升效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:40:36