Add custom HTTP Response Header to IIS

HTTP Response headers are name-value pairs of strings sent back from a server with the content user requested. They are typically used to transfer technical information like how a browser should cache content, what type of content it is, the software running on the server etc. Increasingly, HTTP Response headers have been used to transmit security policies to the browser. By passing security policies back to the client in this fashion, hosts can ensure a much safer browsing experience for their visitors and also reduce the risk for everyone involved. This script will create custom HTTP Response Header to IIS site. 

Steps :

  1. Download the attache powershell script (.ps1 file).
  2. Open Windows PowerShell Command Prompt with Administrative previllage
  3. Run the following command...

PowerShell
Edit|Remove
&"<Directory Path>\SetHTTPResponseHeader.ps1" "Your IIS Site Name" "Custom HTTP Header Name" "Value"

 

 Source code:

 

PowerShell
Edit|Remove
param 
( 
   [string]$WebSiteName = $(throw "The web site name must be provided."), 
   [string]$HeaderName = $(throw "The header name must be provided."), 
   [string]$HeaderValue = $(throw "The header vale must be provided.") 
) 
cls 
# Initialize the default script exit code. 
$exitCode = 0 
 
try 
{ 
    $iisVersion = Get-ItemProperty "HKLM:\software\microsoft\InetStp"; 
    if ($iisVersion.MajorVersion -eq 7) 
    { 
        if ($iisVersion.MinorVersion -ge 5) 
        { 
            Import-Module WebAdministration; 
        }            
        else 
        { 
            if (-not (Get-PSSnapIn | Where {$_.Name -eq "WebAdministration";})) { 
                Add-PSSnapIn WebAdministration; 
            } 
        } 
    } 
     
    $PSPath =  'MACHINE/WEBROOT/APPHOST/' + $WebSiteName 
     
    Remove-WebConfigurationProperty -PSPath $PSPath -Name . -Filter system.webServer/httpProtocol/customHeaders -AtElement @{name =$HeaderName } 
              
    $iis = new-object Microsoft.Web.Administration.ServerManager 
    $config = $iis.GetWebConfiguration($WebSiteName#i.e. "Default Web Site" 
    $httpProtocolSection = $config.GetSection("system.webServer/httpProtocol") 
    $customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders") 
 
    $addElement = $customHeadersCollection.CreateElement("add") 
    $addElement["name"] = $HeaderName 
    $addElement["value"] = $HeaderValue 
 
    $customHeadersCollection.Add($addElement) 
 
    $iis.CommitChanges()  
    write-host $iis 
} 
Catch [System.Exception] 
{ 
    $exitCode = 1 
    write-host "Error" $_.Exception.Message 
} 
# Indicate the resulting exit code to the calling process. 
if ($exitCode -gt 0) 
{ 
    "`nERROR: Operation failed with error code $exitCode." 
} 
"`nDone." 
exit $exitCode