다음을 통해 공유

使用 Azure PowerShell 创建支持基于 URL 路径的重定向的应用程序网关

创建应用程序网关时,可以使用 Azure PowerShell 配置基于 URL 的路由规则。 在本教程中,使用虚拟机规模集创建后端池。 然后,创建 URL 路由规则,根据请求 URL 路径将 Web 流量重定向到相应的后端池。 创建应用程序网关时,可以使用 Azure PowerShell 配置基于 URL 的高级路由规则

本教程介绍生产就绪配置,包括安全最佳做法、性能优化和监视设置。

本教程中,您将学习如何:

  • 设置网络基础结构
  • 使用基于路径的路由创建应用程序网关
  • 添加用于 URL 重定向的侦听器和路由规则
  • 为后端池创建虚拟机规模集
  • 测试应用程序网关路由和重定向功能

下面的示例演示来自端口 8080 和 8081 并定向到相同后端池的站点流量:

URL 路由和重定向体系结构示意图。

Prerequisites

如果需要,可以使用 Azure CLI 完成此过程。

在开始本教程之前,请确保具备:

  • 有效的 Azure 订阅。 如果没有试用版,请创建 试用版
  • 本地安装的 Azure PowerShell 模块版本 5.4.1 或更高版本
  • 目标 Azure 订阅的参与者或所有者权限
  • 基本了解应用程序网关概念和 PowerShell 脚本

Note

建议使用 Azure Az PowerShell 模块与 Azure 交互。 若要开始,请参阅安装 Azure PowerShell。 若要了解如何迁移到 Az PowerShell 模块,请参阅 将 Azure PowerShell 从 AzureRM 迁移到 Az

如果选择在本地安装和使用 PowerShell,本教程需要 Azure PowerShell 模块 5.4.1 或更高版本。 若要查找版本,请运行 Get-Module -ListAvailable Az。 如果需要进行升级,请参阅 Install Azure PowerShell module(安装 Azure PowerShell 模块)。 如果在本地运行 PowerShell,则还需运行 Connect-AzAccount -Environment AzureChinaCloud 以创建与 Azure 的连接。

创建资源组

资源组是在其中部署和管理 Azure 资源的逻辑容器。 使用 New-AzResourceGroup 创建 Azure 资源组。

# Define variables for consistent naming and easier management
$resourceGroupName = "myResourceGroupAG"
$location = "chinanorth2"

# Create the resource group
New-AzResourceGroup -Name $resourceGroupName -Location $location

# Verify the resource group creation
Write-Output "Resource group '$resourceGroupName' created successfully in '$location'"

创建网络资源

使用 New-AzVirtualNetworkSubnetConfig 创建 myBackendSubnetmyAGSubnet 的子网配置。 使用 New-AzVirtualNetwork 和子网配置创建名为 myVNet 的虚拟网络。 最后,使用 New-AzPublicIpAddress 创建名为 myAGPublicIPAddress 的公共 IP 地址。 这些资源提供与应用程序网关及其关联资源的网络连接。

Important

应用程序网关子网(myAGSubnet)只能包含应用程序网关。 此子网中不允许其他任何资源。 使用 New-AzVirtualNetworkSubnetConfig 创建 myBackendSubnetmyAGSubnet 的子网配置。 应用程序网关需要一个至少为 /24 CIDR 的专用子网,以确保正确操作和未来的扩展。 使用 New-AzVirtualNetwork 和子网配置创建名为 myVNet 的虚拟网络。 最后,使用标准 SKU 和静态分配创建公共 IP 地址,以提高 使用 New-AzPublicIpAddress 的安全性和性能。

# Create backend subnet configuration with appropriate CIDR for scale sets
$backendSubnetConfig = New-AzVirtualNetworkSubnetConfig `
  -Name myBackendSubnet `
  -AddressPrefix 10.0.1.0/24

# Create Application Gateway subnet - dedicated subnet required
$agSubnetConfig = New-AzVirtualNetworkSubnetConfig `
  -Name myAGSubnet `
  -AddressPrefix 10.0.2.0/24

New-AzVirtualNetwork `
  -ResourceGroupName myResourceGroupAG `
  -Location chinanorth2 `
  -Name myVNet `
  -AddressPrefix 10.0.0.0/16 `
  -Subnet $backendSubnetConfig, $agSubnetConfig

New-AzPublicIpAddress `
  -ResourceGroupName myResourceGroupAG `
  -Location chinanorth2 `
  -Name myAGPublicIPAddress `
  -AllocationMethod Dynamic

创建应用程序网关

本部分将创建支持应用程序网关的资源,然后最终创建应用程序网关。 创建的资源包括:

  • IP 配置和前端端口 - 将先前创建的子网关联到应用程序网关,并分配一个端口以用于访问它。
  • 默认池 - 所有应用程序网关必须至少具有一个后端服务器池。
  • 默认侦听器和规则 - 默认侦听器侦听已分配的端口上的流量,默认规则将流量发送到默认池。

创建 IP 配置和前端端口

使用 New-AzApplicationGatewayIPConfiguration 将前面创建的 myAGSubnet 关联到应用程序网关。 使用 New-AzApplicationGatewayFrontendIPConfigmyAGPublicIPAddress 分配给应用程序网关。 然后使用 New-AzApplicationGatewayFrontendPort 创建 HTTP 端口。

# Get the virtual network and subnet references
$vnet = Get-AzVirtualNetwork `
  -ResourceGroupName myResourceGroupAG `
  -Name myVNet

$subnet=$vnet.Subnets[0]

# Get the public IP address
$pip = Get-AzPublicIpAddress `
  -ResourceGroupName myResourceGroupAG `
  -Name myAGPublicIPAddress

# Create IP configuration for the Application Gateway
$gipconfig = New-AzApplicationGatewayIPConfiguration `
  -Name myAGIPConfig `
  -Subnet $subnet

# Create frontend IP configuration
$fipconfig = New-AzApplicationGatewayFrontendIPConfig `
  -Name myAGFrontendIPConfig `
  -PublicIPAddress $pip

# Create frontend port for HTTP traffic
$frontendport = New-AzApplicationGatewayFrontendPort `
  -Name myFrontendPort `
  -Port 80

Write-Output "Application Gateway IP configurations created successfully"

创建默认池和设置

使用 New-AzApplicationGatewayBackendAddressPool 为应用程序网关创建名为 appGatewayBackendPool 的默认后端池。 使用 New-AzApplicationGatewayBackendHttpSettings 配置后端池的设置。

# Create default backend pool
$defaultPool = New-AzApplicationGatewayBackendAddressPool `
  -Name appGatewayBackendPool

# Create backend HTTP settings with optimized configuration
$poolSettings = New-AzApplicationGatewayBackendHttpSettings `
  -Name myPoolSettings `
  -Port 80 `
  -Protocol Http `
  -CookieBasedAffinity Enabled `
  -RequestTimeout 120

创建默认侦听器和规则

若要使应用程序网关能够适当地将流量路由到后端池,则需要侦听器。 在本教程中,将为不同的路由方案创建多个侦听器。 第一个基本侦听器应在根 URL 收到流量。 其他侦听器应在特定 URL 路径(如 http://203.0.113.1:8080/images/http://203.0.113.1:8081/video/)处收到流量。

使用 New-AzApplicationGatewayHttpListener 以及前面创建的前端配置和前端端口创建名为 defaultListener 的侦听器。 侦听器需要使用规则来了解哪个后端池使用传入流量。 使用 New-AzApplicationGatewayRequestRoutingRule 创建一个名为 rule1 的基本规则。

# Create default HTTP listener
$defaultlistener = New-AzApplicationGatewayHttpListener `
  -Name defaultListener `
  -Protocol Http `
  -FrontendIPConfiguration $fipconfig `
  -FrontendPort $frontendport

# Create basic routing rule that directs traffic to default pool
$frontendRule = New-AzApplicationGatewayRequestRoutingRule `
  -Name rule1 `
  -RuleType Basic `
  -HttpListener $defaultlistener `
  -BackendAddressPool $defaultPool `
  -BackendHttpSettings $poolSettings `
  -Priority 100

Write-Output "Default listener and routing rule created successfully"

创建应用程序网关

现在已创建所需的支持资源,请使用 New-AzApplicationGatewaySku 为名为 myAppGateway 的应用程序网关指定参数,然后再使用 New-AzApplicationGateway 创建它。

# Create SKU configuration for Application Gateway v2
$sku = New-AzApplicationGatewaySku `
  -Name Standard_Medium `
  -Tier Standard `
  -Capacity 2

New-AzApplicationGateway `
  -Name myAppGateway `
  -ResourceGroupName myResourceGroupAG `
  -Location chinanorth2 `
  -BackendAddressPools $defaultPool `
  -BackendHttpSettingsCollection $poolSettings `
  -FrontendIpConfigurations $fipconfig `
  -GatewayIpConfigurations $gipconfig `
  -FrontendPorts $frontendport `
  -HttpListeners $defaultlistener `
  -RequestRoutingRules $frontendRule `
  -Sku $sku

添加后端池和端口

可以使用Add-AzApplicationGatewayBackendAddressPool 将后端地址池添加到应用程序网关。 在此示例中,将为路由特定内容类型创建 imagesBackendPoolvideoBackendPool 。 使用 Add-AzApplicationGatewayFrontendPort 为池添加前端端口。 使用 Set-AzApplicationGateway 提交对应用程序网关所做的更改。

# Get the current Application Gateway configuration
$appgw = Get-AzApplicationGateway `
  -ResourceGroupName myResourceGroupAG `
  -Name myAppGateway

# Add specialized backend pools for different content types
Add-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name imagesBackendPool

Add-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name videoBackendPool

# Add frontend ports for specialized listeners
Add-AzApplicationGatewayFrontendPort `
  -ApplicationGateway $appgw `
  -Name bport `
  -Port 8080

Add-AzApplicationGatewayFrontendPort `
  -ApplicationGateway $appgw `
  -Name rport `
  -Port 8081

# Apply the configuration changes
Set-AzApplicationGateway -ApplicationGateway $appgw

添加侦听器和规则

Add listeners

使用 Add-AzApplicationGatewayHttpListener 添加路由流量所需的名为 backendListener 和 redirectedListener 的侦听器

# Get the current Application Gateway configuration
$appgw = Get-AzApplicationGateway `
  -ResourceGroupName myResourceGroupAG `
  -Name myAppGateway

# Get frontend port references
$backendPort = Get-AzApplicationGatewayFrontendPort `
  -ApplicationGateway $appgw `
  -Name bport

$redirectPort = Get-AzApplicationGatewayFrontendPort `
  -ApplicationGateway $appgw `
  -Name rport

# Get frontend IP configuration
$fipconfig = Get-AzApplicationGatewayFrontendIPConfig `
  -ApplicationGateway $appgw

# Add listeners for different ports
Add-AzApplicationGatewayHttpListener `
  -ApplicationGateway $appgw `
  -Name backendListener `
  -Protocol Http `
  -FrontendIPConfiguration $fipconfig `
  -FrontendPort $backendPort

Add-AzApplicationGatewayHttpListener `
  -ApplicationGateway $appgw `
  -Name redirectedListener `
  -Protocol Http `
  -FrontendIPConfiguration $fipconfig `
  -FrontendPort $redirectPort

# Apply the configuration changes
Set-AzApplicationGateway -ApplicationGateway $appgw

添加默认 URL 路径映射

URL 路径映射可确保将特定的 URL 路由到特定的后端池。 可以使用 New-AzApplicationGatewayPathRuleConfigAdd-AzApplicationGatewayUrlPathMapConfig 创建名为 imagePathRulevideoPathRule 的 URL 路径映射。

# Get the current Application Gateway configuration
$appgw = Get-AzApplicationGateway `
  -ResourceGroupName myResourceGroupAG `
  -Name myAppGateway

# Get backend HTTP settings
$poolSettings = Get-AzApplicationGatewayBackendHttpSettings `
  -ApplicationGateway $appgw `
  -Name myPoolSettings

# Get backend address pools
$imagePool = Get-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name imagesBackendPool

$videoPool = Get-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name videoBackendPool

$defaultPool = Get-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name appGatewayBackendPool

# Create path rules for different content types
$imagePathRule = New-AzApplicationGatewayPathRuleConfig `
  -Name imagePathRule `
  -Paths "/images/*" `
  -BackendAddressPool $imagePool `
  -BackendHttpSettings $poolSettings

$videoPathRule = New-AzApplicationGatewayPathRuleConfig `
  -Name videoPathRule `
  -Paths "/video/*" `
  -BackendAddressPool $videoPool `
  -BackendHttpSettings $poolSettings

# Add URL path map configuration
Add-AzApplicationGatewayUrlPathMapConfig `
  -ApplicationGateway $appgw `
  -Name urlpathmap `
  -PathRules $imagePathRule, $videoPathRule `
  -DefaultBackendAddressPool $defaultPool `
  -DefaultBackendHttpSettings $poolSettings

# Apply the configuration changes
Set-AzApplicationGateway -ApplicationGateway $appgw

添加重定向配置

可以使用 Add-AzApplicationGatewayRedirectConfiguration 为侦听器配置重定向。

# Get the current Application Gateway configuration
$appgw = Get-AzApplicationGateway `
  -ResourceGroupName $resourceGroupName `
  -Name myAppGateway

# Get the target listener for redirection
$backendListener = Get-AzApplicationGatewayHttpListener `
  -ApplicationGateway $appgw `
  -Name backendListener

# Add redirection configuration with query string and path preservation
$redirectConfig = Add-AzApplicationGatewayRedirectConfiguration `
  -ApplicationGateway $appgw `
  -Name redirectConfig `
  -RedirectType Found `
  -TargetListener $backendListener `
  -IncludePath $true `
  -IncludeQueryString $true

# Apply the configuration changes
Set-AzApplicationGateway -ApplicationGateway $appgw

Write-Output "Redirection configuration added successfully"
Write-Output "Redirect type: HTTP 302 Found"
Write-Output "Target: backendListener (Port 8080)"
Write-Output "Preserves: Path and Query String"

添加重定向 URL 路径映射

为重定向方案创建单独的 URL 路径映射。 此映射将处理端口 8081 上的流量,并将特定路径重定向到端口 8080 上的相应侦听器。

# Get the current Application Gateway configuration
$appgw = Get-AzApplicationGateway `
  -ResourceGroupName $resourceGroupName `
  -Name myAppGateway

# Get references to existing configurations
$poolSettings = Get-AzApplicationGatewayBackendHttpSettings `
  -ApplicationGateway $appgw `
  -Name myPoolSettings

$defaultPool = Get-AzApplicationGatewayBackendAddressPool `
  -ApplicationGateway $appgw `
  -Name appGatewayBackendPool

$redirectConfig = Get-AzApplicationGatewayRedirectConfiguration `
  -ApplicationGateway $appgw `
  -Name redirectConfig

# Create path rule for redirection - images traffic will be redirected
$redirectPathRule = New-AzApplicationGatewayPathRuleConfig `
  -Name redirectPathRule `
  -Paths "/images/*" `
  -RedirectConfiguration $redirectConfig

# Add redirection path map configuration
Add-AzApplicationGatewayUrlPathMapConfig `
  -ApplicationGateway $appgw `
  -Name redirectpathmap `
  -PathRules $redirectPathRule `
  -DefaultBackendAddressPool $defaultPool `
  -DefaultBackendHttpSettings $poolSettings

# Apply the configuration changes
Set-AzApplicationGateway -ApplicationGateway $appgw

Write-Output "Redirection URL path map added successfully"
Write-Output "Redirection rule: /images/* on port 8081 -> port 8080"

添加路由规则

路由规则可将 URL 映射与所创建的侦听器相关联。 可以使用 Add-AzApplicationGatewayRequestRoutingRule 添加名为 defaultRule 和 redirectedRule 的规则

$appgw = Get-AzApplicationGateway `
  -ResourceGroupName myResourceGroupAG `
  -Name myAppGateway

$backendlistener = Get-AzApplicationGatewayHttpListener `
  -ApplicationGateway $appgw `
  -Name backendListener

$redirectlistener = Get-AzApplicationGatewayHttpListener `
  -ApplicationGateway $appgw `
  -Name redirectedListener

$urlPathMap = Get-AzApplicationGatewayUrlPathMapConfig `
  -ApplicationGateway $appgw `
  -Name urlpathmap

$redirectPathMap = Get-AzApplicationGatewayUrlPathMapConfig `
  -ApplicationGateway $appgw `
  -Name redirectpathmap

Add-AzApplicationGatewayRequestRoutingRule `
  -ApplicationGateway $appgw `
  -Name defaultRule `
  -RuleType PathBasedRouting `
  -HttpListener $backendlistener `
  -UrlPathMap $urlPathMap

Add-AzApplicationGatewayRequestRoutingRule `
  -ApplicationGateway $appgw `
  -Name redirectedRule `
  -RuleType PathBasedRouting `
  -HttpListener $redirectlistener `
  -UrlPathMap $redirectPathMap

Set-AzApplicationGateway -ApplicationGateway $appgw

创建虚拟机规模集

在此示例中,将创建三个虚拟机规模集以支持所创建的三个后端池。 规模集名为 myvmss1myvmss2myvmss3。 每个规模集包含两个在其上安装了 IIS 的虚拟机实例。 配置 IP 设置时将规模集分配给后端池。

Important

在运行脚本之前,将 <username><password> 替换为您自己的值。 使用符合 Azure 安全要求的强密码。 安全说明:将 <username><password> 替换为安全凭据。 请考虑在生产方案中使用 Azure Key Vault 进行凭据管理。

# Get network and Application Gateway references
$vnet = Get-AzVirtualNetwork `
  -ResourceGroupName myResourceGroupAG `
  -Name myVNet

$appgw = Get-AzApplicationGateway `
  -ResourceGroupName myResourceGroupAG `
  -Name myAppGateway

# Get backend pool references
$backendPool = Get-AzApplicationGatewayBackendAddressPool `
  -Name appGatewayBackendPool `
  -ApplicationGateway $appgw

$imagesPool = Get-AzApplicationGatewayBackendAddressPool `
  -Name imagesBackendPool `
  -ApplicationGateway $appgw

$videoPool = Get-AzApplicationGatewayBackendAddressPool `
  -Name videoBackendPool `
  -ApplicationGateway $appgw

# Create three scale sets with improved configuration
for ($i=1; $i -le 3; $i++)
{
  if ($i -eq 1)
  {
     $poolId = $backendPool.Id
  }
  if ($i -eq 2) 
  {
    $poolId = $imagesPool.Id
  }
  if ($i -eq 3)
  {
    $poolId = $videoPool.Id
  }

  $ipConfig = New-AzVmssIpConfig `
    -Name myVmssIPConfig$i `
    -SubnetId $vnet.Subnets[1].Id `
    -ApplicationGatewayBackendAddressPoolsId $poolId

  # Create scale set configuration with modern VM size and settings
  $vmssConfig = New-AzVmssConfig `
    -Location chinanorth2 `
    -SkuCapacity 2 `
    -SkuName Standard_DS2 `
    -UpgradePolicyMode Automatic

  # Configure storage profile with Windows Server 2022
  Set-AzVmssStorageProfile $vmssConfig `
    -ImageReferencePublisher MicrosoftWindowsServer `
    -ImageReferenceOffer WindowsServer `
    -ImageReferenceSku 2016-Datacenter `
    -ImageReferenceVersion latest `
    -OsDiskCreateOption FromImage

  Set-AzVmssOsProfile $vmssConfig `
    -AdminUsername <username> `
    -AdminPassword "<password>" `
    -ComputerNamePrefix myvmss$i

  # Add network interface configuration
  Add-AzVmssNetworkInterfaceConfiguration `
    -VirtualMachineScaleSet $vmssConfig `
    -Name myVmssNetConfig$i `
    -Primary $true `
    -IPConfiguration $ipConfig

  New-AzVmss `
    -ResourceGroupName myResourceGroupAG `
    -Name myvmss$i `
    -VirtualMachineScaleSet $vmssConfig

  Write-Output "Virtual Machine Scale Set myvmss$i created successfully"
}

Write-Output "All Virtual Machine Scale Sets created successfully"

Install IIS

以下脚本在每个规模集中的虚拟机上安装 IIS,并对其进行配置,以便根据它们提供服务的后端池显示不同的内容。

$publicSettings = @{ "fileUris" = (,"https://raw.githubusercontent.com/Azure/azure-docs-powershell-samples/master/application-gateway/iis/appgatewayurl.ps1"); 
  "commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File appgatewayurl.ps1" }

# Install IIS on all scale sets
for ($i=1; $i -le 3; $i++)
{
  $vmss = Get-AzVmss -ResourceGroupName myResourceGroupAG -VMScaleSetName myvmss$i

  Add-AzVmssExtension -VirtualMachineScaleSet $vmss `
    -Name "customScript" `
    -Publisher "Microsoft.Compute" `
    -Type "CustomScriptExtension" `
    -TypeHandlerVersion 1.8 `
    -Setting $publicSettings

  Update-AzVmss `
    -ResourceGroupName myResourceGroupAG `
    -Name myvmss$i `
    -VirtualMachineScaleSet $vmss
}

测试应用程序网关

尽管 IIS 不需要创建应用程序网关,但在本教程中安装了它,以验证 Azure 是否成功创建了应用程序网关。 使用 IIS 测试应用程序网关:

  1. 运行 Get-AzPublicIPAddress 以获取应用程序网关的公共 IP 地址:

    Get-AzPublicIPAddress -ResourceGroupName myResourceGroupAG -Name myAGPublicIPAddress
    
  2. 复制该公共 IP 地址,并将其粘贴到浏览器的地址栏。 For example:

    • http://203.0.113.1 (基准 URL)
    • http://203.0.113.1:8080/images/test.htm (图像路径)
    • http://203.0.113.1:8080/video/test.htm (视频路径)
    • http://203.0.113.1:8081/images/test.htm (重定向测试)

显示测试应用程序网关基 URL 时的默认 IIS 欢迎页的屏幕截图。

将 URL 更改为 http://<ip-address>:8080/images/test.htm,将 <ip-address> 替换为您的 IP 地址,您应该会看到类似于以下示例的内容:

显示访问应用程序网关上的 /images 路径时映像后端池测试页的屏幕截图。

将 URL 更改为 http://<ip-address>:8080/video/test.htm,将 <ip-address> 替换为您的 IP 地址,您应该会看到类似于以下示例的内容:

显示访问应用程序网关上的 /video 路径时的视频后端池测试页的屏幕截图。

现在,将 URL 更改为 http://<ip-address>:8081/images/test.htm,将您的 IP 地址替换为 <ip-address>,然后您应该会看到流量被重定向回 http://<ip-address>:8080/images 的图像后端池。

Performance monitoring

监视关键应用程序网关指标以获得最佳性能:

  • 请求计数:处理的请求总数
  • 响应时间:请求的平均响应时间
  • 异常服务器计数:异常后端服务器数
  • 吞吐量:通过应用程序网关传输数据传输速率

清理资源

如果不再需要资源组、应用程序网关和所有相关资源,可以使用 Remove-AzResourceGroup 将其删除。

Remove-AzResourceGroup -Name myResourceGroupAG

Next steps

了解了使用应用程序网关的基于 URL 路径的重定向后,请浏览以下高级方案:

More resources