假设需要允许来源为localhost.*.example.com下所有二级域名的访问,在nginx中只需要类似这样配置即可:

    location / {
		set $match "";
		# 支持http及https
		if ($http_origin ~* 'https?://(localhost|.*\.example\.com)') {
		set $match "true";
		}
		
		if ($match = "true") {
			add_header Access-Control-Allow-Origin "$http_origin";
			add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
			add_header Access-Control-Allow-Methods GET,POST,OPTIONS,DELETE;
			add_header Access-Control-Allow-Credentials true;
		}
		# 处理OPTIONS请求
		if ($request_method = 'OPTIONS') {
			return 204;
		}
	}

当然通过正则也可以详细指定若干个允许访问的域名来源。

Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐