I'm trying to make a PS script that creates an IIS web page, configures a reverse proxy via URL Rewrite and I'm stuck on how to add allowed server variables via PowerShell.

Does anyone know how to add these variables via powershell for the IIS website?
FYI adding server variable on server level by powershell:
Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="RESPONSE_SERVER"}
this will add the following configuration in applicationhost.config
<system.webServer>
...
<rewrite>
...
<allowedServerVariables>
<add name="RESPONSE_SERVER" />
</allowedServerVariables>
...
</rewrite>
</system.webServer>
Updated 2024/09/24
this answer works with PowerShell 7+
Import-Module IISAdministration
function Enable-IisServerVariable($variable) {
$section = Get-IISConfigSection -SectionPath "system.webServer/rewrite/allowedServerVariables"
$collection = Get-IISConfigCollection -ConfigElement $section
$existingVariables = $collection | ForEach-Object { $_.Attributes["name"].Value }
if (-not ($existingVariables -contains $variable)) {
New-IISConfigCollectionElement -ConfigCollection $collection -ConfigAttribute @{"Name" = $variable}
Write-Host "Server variable '$variable' has been added."
} else {
Write-Host "Server variable '$variable' is already enabled."
}
}
function Enable-ReverseProxyHeaderForwarding() {
foreach ($variable in @("HTTP_X_FORWARDED_PROTO", "HTTP_X_FORWARDED_HOST", "HTTP_X_FORWARDED_FOR")) {
Enable-IisServerVariable $variable
}
}
Enable-ReverseProxyHeaderForwarding
Original Answer
as noted in @matija's answer, you will need to ensure you have the web admin module loaded:
Import-Module WebAdministration
then, building on @lia's answer, you can define a function to add multiple variables in an idempotent fashion like this:
function Enable-ReverseProxyHeaderForwarding() {
$requiredVariables = @("HTTP_X_FORWARDED_PROTO", "HTTP_X_FORWARDED_HOST", "HTTP_X_FORWARDED_FOR")
$existingVariables = Get-WebConfiguration -Filter "/system.webServer/rewrite/allowedServerVariables/add" -PSPath "IIS:\Sites\" | ForEach-Object { $_.name }
foreach ($variable in $requiredVariables) {
if (-not ($existingVariables -contains $variable)) {
Add-WebConfiguration "/system.webServer/rewrite/allowedServerVariables" -value @{name = $variable }
}
}
}
and then execute the function:
Enable-ReverseProxyHeaderForwarding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With