In this Article, we will look at a script that sets all websites to use HTTPS instead of HTTP.
Making sure our website is secure for our visitors and also to make search engines like Google happy, we must have HTTPS enabled on all our websites.
The best way to handle this is to place the code in our applicationHost.config file so it affects all websites, rather than editing each web.config file.
I ran this on one of my [ARR Servers] ([Application Request Routing]), which is in a [Shared-Configuration] with several others.
Once you update one, all get updated.
Since the ARR is the [Front-End], this is the only place we need to invoke this command.
[PowerShell - IIS set all websites to only use HTTPS]
CFFCS | CarrzSynEdit: | PS (PowerShell)
$path = "G:\IIS_Config\applicationHost.config"
[xml]$xml = Get-Content $path

$globalRulesNode = $xml.SelectSingleNode("//system.webServer/rewrite/globalRules")

# Create the HTTPS Force Rule

$rule = $xml.CreateElement("rule")
$rule.SetAttribute("name", "Global Force HTTPS")
$rule.SetAttribute("stopProcessing", "true")

# Match anything

$match = $xml.CreateElement("match")
$match.SetAttribute("url", "(.*)")
$rule.AppendChild($match) | Out-Null

# Condition: Check if HTTPS is OFF

$conditions = $xml.CreateElement("conditions")
$add = $xml.CreateElement("add")
$add.SetAttribute("input", "{HTTPS}")
$add.SetAttribute("pattern", "^OFF$")
$conditions.AppendChild($add) | Out-Null
$rule.AppendChild($conditions) | Out-Null

# Action: Redirect to the https version of the host and path

$action = $xml.CreateElement("action")
$action.SetAttribute("type", "Redirect")
$action.SetAttribute("url", "https://{HTTP_HOST}/{R:1}") 
$action.SetAttribute("redirectType", "Permanent")
$rule.AppendChild($action) | Out-Null

# Add to Global Rules (Prepending so it runs first)

$globalRulesNode.PrependChild($rule) | Out-Null
$xml.Save($path)

Write-Host "Success: Global HTTPS redirect added." -ForegroundColor Green


[PowerShell - iisreset]
CFFCS | CarrzSynEdit: | PS (PowerShell)
Stop-Service WAS -Force
Start-Service W3SVC

Other Articles Related to this Entry.