I am using an azure devops step to try create https redirect rule in IIS using the Manage IIS task.
I am using the following "Additional appcmd.exe commands"
set config -section:system.webServer/rewrite/rules /+"[name='http_redirect',enabled='True']" /commit:apphost
set config -section:system.webServer/rewrite/rules.[name='http_redirect'] /match.url:"(.*)" /match.ignoreCase:true /commit:apphost
set config -section:system.webServer/rewrite/rules.[name='http_redirect'].conditions/add /+"[input='{HTTPS}',pattern='off']" /commit:apphost
set config -section:system.webServer/rewrite/rules.[name='http_redirect'].action /+"[type='Redirect',url='https://{HOST_NAME}/{R:1}',redirectType='Found']" /commit:apphost
It seems that the first command runs as a blank rule is created, but the second one fails trying to find the rule by the name http_redirect
You could use below command to set URL rewrite globally:
appcmd.exe set config -section:system.webServer/rewrite/globalRules /+"[name='http_redirect']" /commit:apphost
appcmd.exe set config -section:system.webServer/rewrite/globalRules /[name='http_redirect'].match.url:"(.*)" /commit:apphost
appcmd.exe set config -section:system.webServer/rewrite/globalRules /+"[name='http_redirect'].conditions.[input='{HTTPS}',pattern='off']" /commit:apphost
appcmd.exe set config -section:system.webServer/rewrite/globalRules /[name='http_redirect'].action.type:"Redirect" /[name='http_redirect'].action.url:"https://{HTTP_HOST}/{R:1}" /[name='http_redirect'].action.redirectType:"Found" /commit:apphost
Note: do not use {HOST_NAME},use {HTTP_HOST}.
to apply for specific site use this command:
appcmd.exe set config "aspsite" -section:system.webServer/rewrite/rules /+"[name='http_redirect']" /commit:apphost
appcmd.exe set config "aspsite" -section:system.webServer/rewrite/rules /[name='http_redirect'].match.url:"(.*)" /commit:apphost
appcmd.exe set config "aspsite" -section:system.webServer/rewrite/rules /+"[name='http_redirect'].conditions.[input='{HTTPS}',pattern='off']" /commit:apphost
appcmd.exe set config "aspsite" -section:system.webServer/rewrite/rules /[name='http_redirect'].action.type:"Redirect" /[name='http_redirect'].action.url:"https://{HOST_NAME}/{R:1}" /[name='http_redirect'].action.redirectType:"Found" /commit:apphost
Edit:
power-shell command to add rule:
import-module webAdministration
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webserver/rewrite/GlobalRules" -name "." -value #{name='HTTP to HTTPS Redirect'; patternSyntax='ECMAScript'; stopProcessing='True'}
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webserver/rewrite/GlobalRules/rule[#name='HTTP to HTTPS Redirect']/match" -name url -value "(.*)"
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webserver/rewrite/GlobalRules/rule[#name='HTTP to HTTPS Redirect']/conditions" -name "." -value #{input="{HTTPS}"; pattern='^OFF$'}
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/rewrite/globalRules/rule[#name='HTTP to HTTPS Redirect']/action" -name "type" -value "Redirect"
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/rewrite/globalRules/rule[#name='HTTP to HTTPS Redirect']/action" -name "url" -value "https://{HTTP_HOST}/{R:1}"
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/rewrite/globalRules/rule[#name='HTTP to HTTPS Redirect']/action" -name "redirectType" -value "SeeOther"
Related
I am trying to add a new listener to existing Azure application gateway using powershell script. Here's the command I have used.
Add-AzApplicationGatewayHttpListener -ApplicationGateway $Appgw -Name $listenerName -FrontendIPConfiguration $fipconfig -FrontendPort $port -SslCertificate $cert -HostName $hostName -Protocol "Https" -Debug
All the variables are correctly initialized. Command executes well and return ApplicationGateway object which seems normal. However the newly added listener is not visible in Azure portal. After watching carefully the new listener in ApplicationGateway object (in powershell) it just show below resource path,
/subscriptions/<subscription-id>/resourceGroups/ResourceGroupNotSet/providers/Microsoft.Network/applicationGateways/ApplicationGatewayNameNotSet/httpListeners/<new-listener-name>
two things doesn't seem normal here,
ResourceGroupNotSet
ApplicationGatewayNameNotSet
Can anyone please suggest what could be the reason behind this? and why the listener is not shown in portal at all?
According to my test, if we want to add HTTP listener to existing Azure Application gateway with Powershell, we need to run the command Set-AzApplicationGateway -ApplicationGateway $appgw after you run the command Add-AzApplicationGatewayHttpListener. Because the command Add-AzApplicationGatewayHttpListener just will create a new HTTP listener but it will not update the application gateway.
Connect-AzAccount
$AppGWname ="stantest"
$groupName="stan"
$ipName="appGwPublicFrontendIp"
$portName="port_80"
$listenerName="test1"
$appgw= Get-AzApplicationGateway -Name $AppGWname -ResourceGroupName $groupName
$FEC= Get-AzApplicationGatewayFrontendIPConfig -Name $ipName -ApplicationGateway $appgw
Add-AzApplicationGatewayFrontendPort -ApplicationGateway $appgw -Name $portName -Port 80
$port =Get-AzApplicationGatewayFrontendPort -ApplicationGateway $appgw -Name $portName
Add-AzApplicationGatewayHttpListener -ApplicationGateway $appgw -Name $listenerName -FrontendIPConfiguration $FEC -FrontendPort $port -Protocol Http
Set-AzApplicationGateway -ApplicationGateway $appgw
I am trying to run the following commands to change the settings on an existing Rule in my Azure Application Gateway:
$updatedAppGW = Set-AzureRmApplicationGatewayRequestRoutingRule -ApplicationGateway $AppGW `
-Name $ChosenSubscription.httpsRule `
-RuleType Basic `
-BackendAddressPool $backendPool `
-BackendHttpSettings $httpSettings
# Save Gateway configuration
Write-Host "[$(__LINE__)] Attempting to save changes to the Application Gateway..." -ForegroundColor Cyan
Set-AzureRmApplicationGateway -ApplicationGateway $updatedAppGW | Out-Null
The Set-AzureRmApplicationGatewayRequestRoutingRule command appears to run correctly (silently, at least).
However, when I then try to "save" the Application Gateway configuration with the command Set-AzureRmApplicationGateway I receive the error Set-AzureRmApplicationGateway : Object reference not set to an instance of an object.
I think this is because I'm not using these "Set" commands correctly.
I read online that when I run Set-AzureRmApplicationGatewayRequestRoutingRule, I'm only actually making changes to the Rule in local memory. I then have to save the changes of the Application Gateway.
Is this true? If so... how do I actually save the Application Gateway configuration in this context? Earlier in my script, when using Add-AzureRm commands (such as Add-AzureRmApplicationGatewayBackendAddressPool), I've immediately (following line) run Set-AzureRmApplicationGateway and it has worked as intended.
I have also tried altering the Set-AzureRmApplicationGateway command in the code block at the top of this post to use my original $AppGW variable instead of this $updatedAppGW variable which I think my Set-AzureRmApplicationGatewayRequestRoutingRule command is producing. Neither works - identical error.
EDIT: Additional diagnosis
Adding the following Write-Host output...
Write-Host "[$(__LINE__)] Retrieved AG Rule '$($rule.Name)'." -ForegroundColor Magenta
Write-Host "[$(__LINE__)] Attempting to change this rule to point at Backend Address Pool '$($backendPool.Name)' and HTTP Settings '$($httpSettings.Name)'..." -ForegroundColor Cyan
# Re-retrieve the Application Gateway after saving it earlier
$AppGW = Get-AzureRmApplicationGateway -Name $ChosenSubscription.appGateway -ResourceGroupName $ChosenSubscription.resourceGroup
# Re-retrieve the Backend Address Pool and HTTP Settings that we've created, for the sake of updating the rule
$backendPool = Get-AzureRmApplicationGatewayBackendAddressPool -ApplicationGateway $AppGW -Name $MaintenanceToggleBackendPool
$httpSettings = Get-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $AppGW -Name $MaintenanceToggleHTTPSetting
Write-Host "[$(__LINE__)] `$AppGW.Name $($AppGW.Name)" -ForegroundColor Green
Write-Host "[$(__LINE__)] `$AppGW.ProvisioningState $($AppGW.ProvisioningState)" -ForegroundColor Green
Write-Host "[$(__LINE__)] `$AppGW.OperationalState $($AppGW.OperationalState)" -ForegroundColor Green
$updatedAppGW = Set-AzureRmApplicationGatewayRequestRoutingRule -ApplicationGateway $AppGW `
-Name $ChosenSubscription.httpsRule `
-RuleType Basic `
-BackendAddressPool $backendPool `
-BackendHttpSettings $httpSettings
Write-Host "[$(__LINE__)] `$updatedAppGW.Name $($updatedAppGW.Name)" -ForegroundColor Green
Write-Host "[$(__LINE__)] `$updatedAppGW.ProvisioningState $($updatedAppGW.ProvisioningState)" -ForegroundColor Green
Write-Host "[$(__LINE__)] `$updatedAppGW.OperationalState $($updatedAppGW.OperationalState)" -ForegroundColor Green
# Save Gateway configuration
Write-Host "[$(__LINE__)] Attempting to save changes to the Application Gateway..." -ForegroundColor Cyan
Set-AzureRmApplicationGateway -ApplicationGateway $updatedAppGW | Out-Null
... gives the following console output:
OK, managed to fix the problem myself... sigh
On the Set-AzureRmApplicationGatewayRequestRoutingRule command, you must specify the -HttpListener parameter, or it will fail silently.
# Re-retrieve the Backend Address Pool and HTTP Settings that we've created, for the sake of updating the rule
$backendPool = Get-AzureRmApplicationGatewayBackendAddressPool -ApplicationGateway $AppGW -Name $MaintenanceToggleBackendPool
$httpSettings = Get-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $AppGW -Name $MaintenanceToggleHTTPSetting
$httpListener = Get-AzureRmApplicationGatewayHttpListener -ApplicationGateway $AppGW -Name "HttpListenerTest"
$updatedAppGW = Set-AzureRmApplicationGatewayRequestRoutingRule -ApplicationGateway $AppGW `
-Name $ChosenSubscription.httpsRule `
-RuleType Basic `
-BackendAddressPool $backendPool `
-BackendHttpSettings $httpSettings `
-HttpListener $httpListener
This is why the Set-AzureRmApplicationGateway command wasn't working properly - it had a malformed RequestRoutingRule in its memory.
let's say the Application gateway receives a request http://contoso.com/images and is configured to forward that to backendserver.contoso.com. Using a path based routing rule (/images/* for example).
I want the application gateway not to retain the /images path in the request URL. I need this to be truncated, in which case the request will simply be http://contoso.com/. Any path after the /images will remain intact though.
Is it possible? Any help/clue is greatly appreciated.
Yes you could do this today with PowerShell/CLI. In the backend http setting associated with the pool, please specify a -Path parameter. For example -
Add-AzureRmApplicationGatewayBackendHttpSettings -Path "/" -Name setting1 -Port 80 -Protocol Http -CookieBasedAffinity Disabled
When -Path is not specified at all, incoming request is routed to backend as is - which is the default behavior. When specified as "/" it removes the matching path from URI. If specified as a non-null value, then the specified value is used in place of matched path.
Amsrivas and Stephens answer is correct, but the poweshell CLI seems to have changed, at least # version 5.5.0 and now you have to perfrom this opperation using the following commands:
# Get gateway object
$AppGw = Get-AzureRmApplicationGateway -Name "YOUR GATEWAY NAME" -ResourceGroupName "YOUR GATEWAY RESOURCE GROUP"
# Show current settings
Get-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $AppGw
# Set path on local object (other values are whatever you want)
Set-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $AppGw -Name "YOUR SETTING NAME" -Port "80" -Protocol "Http" -CookieBasedAffinity "Disabled" -RequestTimeout 30 -Path "/"
# Commit changes back to Azure
$UpdatedAppGw = Set-AzureRmApplicationGateway -ApplicationGateway $AppGw
# Show new settings as applied in Azure
Get-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $UpdatedAppGw
I'm trying to create IIS website on a remote server from another server using powershell. When I execute it, the site has created in local server, not in the remote server.
This is the powershell function. It is in function.ps1 file.
function CreateIISWebsite
{
param (
[string]$iisAppName,
[string]$directoryPath,
[string]$iisAppPoolName,
[string]$rhost,
[string]$un,
[string]$pw
)
$MSDeployExe = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe"
Import-Module WebAdministration
$iisAppPoolDotNetVersion = "v4.0"
#navigate to the app pools root
cd IIS:\AppPools\
#check if the app pool exists
if (Test-Path $iisAppPoolName -pathType container)
{
Remove-Item $iisAppPoolName -recurse
}
#create the app pool
$appPool = New-Item $iisAppPoolName
$appPool | Set-ItemProperty -Name "managedRuntimeVersion" -Value $iisAppPoolDotNetVersion
Set-ItemProperty IIS:\AppPools\$iisAppPoolName managedRuntimeVersion v4.0
Set-ItemProperty -Path IIS:\AppPools\$iisAppPoolName -Name processmodel.identityType -Value 3
Set-ItemProperty -Path IIS:\AppPools\$iisAppPoolName -Name processmodel.username -Value $un
Set-ItemProperty -Path IIS:\AppPools\$iisAppPoolName -Name processmodel.password -Value $pw
#navigate to the sites root
cd IIS:\Sites\
#check if the site exists
if (Test-Path $iisAppName -pathType container)
{
Remove-Item $iisAppName -recurse
}
#create the site
$iisApp = New-Item $iisAppName -bindings #{protocol="http";bindingInformation=":80:" + $iisAppName} -physicalPath $directoryPath
$iisApp | Set-ItemProperty -Name "applicationPool" -Value $iisAppPoolName
}
I call this function like this.
. ./function.ps1
CreateIISWebsite -iisAppName $sitename -directoryPath $path -iisAppPoolName $appPool -rhost $rhost -un $un -pw $pw
Even though i pass ip of the remote server as rhost i have no idea where i need to use it. So IIS site is creating in local successfully. Without using rhost parameter it won't create in server. So I need to use that parameter in correct place in the code.
I have installed Web Deploy in both servers.
Please suggest me a solution.
Configure PowerShell Remoting on the local and remote systems (use Enable-PSRemoting -Force, and then deploy the script to the remote computer by using Invoke-Command.
UPDATE
e.g.
On your local and remote systems write this in an elevated Powershell Command Prompt:
Enable-PSRemoting -Force
Remember also to Set-ExecutionPolicy (See here for more info) to something appropriate on the remote server if you have not already done so.
To invoke the powershell script on the remote machine from your local machine you can then do something like this:
Invoke-Command -ComputerName server01 -File c:\path\to\script.ps1
I need a Powershell command that does the equivalent of adding a website in IIS, but need the bindings for the "Application pool":
So far I can add a website doing this:
New-Item iis:\Sites\swmarket -bindings #{protocol="http";bindingInformation="80:swmarket"} -physicalPath c:\inetpub\wwwroot
But I don't know how to set the "Application pool" in the new website. Any way to see all the bindings?
Set-ItemProperty iis:\Sites\swmarket -Name applicationpool -Value swmarket
Alternatively, with Powershell 3, you could do this:
New-WebAppPool -Name $WebSiteName
New-Website -Name $WebSiteName -ApplicationPool $WebSiteName -HostHeader $WebSiteName -PhysicalPath $PathInfo -Port 80
Set-Content $PathInfo\default.htm “PSCreated Default Page”
Check out the MS Technet description here.