In IIS, the URL Rewrite module can be used to redirect HTTP requests to HTTPS. There exist a lot of information on how to set up rules in the module for HTTP redirection, ssl.com has a good guide.
I wanted to automate the configuration in Azure DevOps, with release pipelines, and preferably in an idempotent way so that the rules are set up with no precondition, and no duplicates rules are created if the HTTP-redirect rule already exists. In the end I used Powershell to catch exit codes from appCmd, and variables that I linked to the release pipeline to insert the website’s name.
# This script sets up HTTP to HTTPS redirect for a website in IIS and can be used in conjunction with Azure DevOps variables
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"
# Set following variable to the name of the IIS website $websiteName = "NameOfTheIISWebsite"
$_ = & $appCmd set config $websiteName -section:system.webServer/rewrite/rules /+"[name='http_redirect_""$websiteName""',enabled='True']" $_ = & $appCmd set config $websiteName -section:system.webServer/rewrite/rules "/[name='http_redirect_""$websiteName""'].match.url:(.*)" $_ = & $appCmd set config $websiteName -section:system.webServer/rewrite/rules "/[name='http_redirect_""$websiteName""'].conditions.[input='{HTTPS}',pattern='Off']"
<# ERRORLEVEL 4312 occurs when trying to find requested collection element which doesn't exist. This error is expected for idempotency. Element does not exist and needs to be added before changed. #> if( $LASTEXITCODE -eq 4312 ) { $_ = & $appCmd set config $websiteName -section:system.webServer/rewrite/rules "/+[name='http_redirect_""$websiteName""'].conditions.[input='{HTTPS}',pattern='Off']" }
$_ = & $appCmd set config $websiteName -section:system.webServer/rewrite/rules "/[name='http_redirect_""$websiteName""'].action.type:Redirect" ` "/[name='http_redirect_""$websiteName""'].action.url:https://{HTTP_HOST}/{R:1}"

