Updated 2024/09/24
this answer works with PowerShell 7+
- import the iis module
Import-Module IISAdministration
- create the following two functions:
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
}
}
- execute the function:
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