王新阳

wangxinyang

IIS web.config设置Access-Control-Allow-Origin

来源:https://www.jianshu.com/p/85855a991275

方法一:添加自定义header,缺点是不支持正则,只能设置一个网站,或者*对全部网站开放

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
	<httpProtocol>
	  <customHeaders>
		   <add name="Access-Control-Allow-Origin" value="https://www.domain1.com" />
	  </customHeaders>
	</httpProtocol>
    </system.webServer>
</configuration>

方法二:使用正则,可添加多个,需要安装微软的URL Rewrite组件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
	<rewrite>
		<outboundRules>
			<rule name="AddCrossDomain">
				<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
				<conditions logicalGrouping="MatchAll" trackAllCaptures="true">
					<add input="{HTTP_ORIGIN}" pattern="(https?://((www\.)?domain1\.com|(www\.)?domain2\.cn))" />
				</conditions>
				<action type="Rewrite" value="{C:0}" />
			</rule>
		</outboundRules>
        </rewrite>
    </system.webServer>
</configuration>

2023-03-15
2024-11-25 星期一 农历十月二十五