ajax 如何配置 apache 以使用 Access-Control-Allow-Origin 标头处理多个域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9466496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:08:00  来源:igfitidea点击:

How to configure apache to handle multiple domains with Access-Control-Allow-Origin header?

ajaxapache

提问by grucha

I want to configure apache to allow XMLHttpRequests from multiple, but not all domains.

我想配置 apache 以允许来自多个域但不是所有域的 XMLHttpRequests。

This works:

这有效:

Header set Access-Control-Allow-Origin "*"

But it's unsafe, I want to allow domains specified by me, so after a bit of googling I got to this:

但这是不安全的,我想允许我指定的域,所以经过一些谷歌搜索后我得到了这个:

Header set Access-Control-Allow-Origin "http://domain1.com http://domain2.com"

But this only picks up first domain, the second is not allowed. How to properly specify multiple domains?

但这只能选择第一个域,第二个是不允许的。如何正确指定多个域?

回答by Ema

you can use SetEnvIf in your .htaccess file or in in vhost file (inside "Directory" group):

您可以在 .htaccess 文件或 vhost 文件(在“目录”组内)中使用 SetEnvIf:

<IfModule mod_headers.c>
   SetEnvIfNoCase Origin "https?://(www\.)?(mydomain\.com|mydomain2\.com)(:\d+)?$" AccessControlAllowOrigin=
Header always append Access-Control-Allow-Origin: "http://domain1.com"
Header always append Access-Control-Allow-Origin: "http://domain2.com"
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </IfModule>

With this code you can allow access from

使用此代码,您可以允许从

  • "mydomain.com" and "mydomain2.com"
  • with or without "www." in front
  • with or without port number
  • http or https
  • “mydomain.com”和“mydomain2.com”
  • 带或不带“www”。在前
  • 有或没有端口号
  • http 或 https

You can add multiple domains separated with | or you can use regexp to configure different subdomains or patterns.

您可以添加多个以 | 分隔的域 或者您可以使用正则表达式来配​​置不同的子域或模式。

回答by Geoffrey

##代码##