Access-control-allow-origin with multiple domains

For IIS 7.5+ and Rewrite 2.0 you can use:

<system.webServer>
   <httpProtocol>
     <customHeaders>
         <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
         <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
     </customHeaders>
   </httpProtocol>
        <rewrite>            
            <outboundRules>
                <clear />                
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?domain1\.com|(.+\.)?domain2\.com|(.+\.)?domain3\.com))" />
                    </conditions>
                    <action type="Rewrite" value="{C:0}" />
                </rule>           
            </outboundRules>
        </rewrite>
 </system.webServer>

Explaining the server variable RESPONSE_Access_Control_Allow_Origin portion:
In Rewrite you can use any string after RESPONSE_ and it will create the Response Header using the rest of the word as the header name (in this case Access-Control-Allow-Origin). Rewrite uses underscores “_” instead of dashes “-” (rewrite converts them to dashes)

Explaining the server variable HTTP_ORIGIN :
Similarly, in Rewrite you can grab any Request Header using HTTP_ as the prefix. Same rules with the dashes (use underscores “_” instead of dashes “-“).

Leave a Comment