Skip to content

Instantly share code, notes, and snippets.

@claytonrothschild
Created December 18, 2018 18:37
Show Gist options
  • Save claytonrothschild/64501d9ced017394e126ca5ca4c216c9 to your computer and use it in GitHub Desktop.
Save claytonrothschild/64501d9ced017394e126ca5ca4c216c9 to your computer and use it in GitHub Desktop.
Use Powershell to Create IIS Rule to Rewrite HTTP to HTTPS
Import-module IISAdministration;
New-IISSite -Name "[YourSiteName]" -PhysicalPath C:\app -BindingInformation "*:81:";
# Download the IIS url-rewrite module
Invoke-WebRequest http://download.microsoft.com/download/D/D/E/DDE57C26-C62C-4C59-A1BB-31D58B36ADA2/rewrite_amd64_en-US.msi -UseBasicParsing -OutFile C:/app/rewrite.msi;
Start-Process msiexec -ArgumentList '/i C:\app\rewrite.msi /qn' -Wait;
rm C:\app\rewrite.msi;
# Produce a rule that looks like this:
# <rewrite>
# <rules>
# <rule name="Rewrite HTTP to HTTPS” stopProcessing=”true”>
# <match url="^(.*)$" />
# <conditions logicalGrouping=”MatchAny”>
# <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" />
# </conditions>
# <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
# </rule>
# </rules>
# </rewrite>
$name = 'Rewrite HTTP to HTTPS';
$inbound = '^(.*)$';
$outbound = 'https://{HTTP_HOST}{REQUEST_URI}';
$pattern = '^http$';
$site = 'IIS:\Sites\[YourSiteName]';
$root = 'system.webServer/rewrite/rules';
$filter = '{0}/rule[@name=''{1}'']' -f $root, $name;
Add-WebConfigurationProperty -PSPath $site -filter $root -name '.' -value @{name=$name; patternSyntax='Regular Expressions'; stopProcessing='False'};
Set-WebConfigurationProperty -PSPath $site -filter "$filter/match" -name 'url' -value $inbound;
Set-WebConfigurationProperty -PSPath $site -filter "$filter/conditions" -name '.' -value @{input='{HTTP_X_FORWARDED_PROTO}'; matchType='0'; pattern=$pattern; ignoreCase='True'; negate='False'};
Set-WebConfigurationProperty -PSPath $site -filter "$filter/action" -name 'type' -value 'Redirect';
Set-WebConfigurationProperty -PSPath $site -filter "$filter/action" -name 'url' -value $outbound;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment