5
header('Access-Control-Allow-Origin: http://splash.example.com');
header('Access-Control-Allow-Credentials: true');

再次您好 Stackoverflow!

在我的网站上,我有一个 ajax 文件ajax.php,我需要多个(子)域来访问它并触发请求。

问题是它适用于上面发布的解决方案,splash.example.com并且example.com在请求中是这样的:

$.ajax({
    ...

    crossDomain: true,
    xhrFields: {
        withCredentials: true
    },

    ...
});

但是没有更简单的方法吗?因为现在它不起作用www.example.com,即使上面发布了解决方案。

我试过把它放在我的htaccess中:

<IfModule mod_headers.c>
    Header add Access-Control-Allow-Origin "http://example.com"
    Header add Access-Control-Allow-Origin "http://www.example.com"
    Header add Access-Control-Allow-Origin "http://splash.example.com"
    Header set Access-Control-Allow-Credentials true
</IfModule>

但这并没有以某种方式起作用。

你们能帮帮我吗?

4

2 回答 2

5

首选方法是读取请求标头,找到来源,在服务器端代码中检查它。如果允许域访问该页面,则在一个Access-Control-Allow-Origin标头中发回原始域。

另一个专业人士:没有其他域用户会看到允许的域列表。每个用户只能看到他自己的域(如果允许)。

于 2013-10-22T13:22:27.363 回答
3

几周前也有这个问题,并找到了这个很好的解决方案。

它允许通过动态查看 HTTP_Origin 标头、提取源主机的子域并在 Access-Control-Allow-Origin 标头中使用它来访问任何子域。

只需将以下内容添加到您的 .htaccess 文件中:

<IfModule mod_headers.c>
<IfModule mod_rewrite.c>
  # Dynamically change the Access-Control-Allow-Origin header to match the sub-domain the request is coming from
  # Define the root domain that is allowed
  SetEnvIf Origin .+ ACCESS_CONTROL_ROOT=example.com
  # Check that the Origin: matches the defined root domain and capture it in an environment var if it does
  RewriteEngine On
  RewriteCond %{ENV:ACCESS_CONTROL_ROOT} !=""
  RewriteCond %{ENV:ACCESS_CONTROL_ORIGIN} =""
  RewriteCond %{ENV:ACCESS_CONTROL_ROOT}&%{HTTP:Origin} ^([^&]+)&(https?://(?:.+?\.)?\1(?::\d{1,5})?)$
  RewriteRule .* - [E=ACCESS_CONTROL_ORIGIN:%2]
  # Set the response header to the captured value if there was a match
  Header set Access-Control-Allow-Origin %{ACCESS_CONTROL_ORIGIN}e env=ACCESS_CONTROL_ORIGIN

  # Allow credentials to enable cookies being sent cross domain, so the user can stay logged is as long as the session file is available to both domains
  Header set Access-Control-Allow-Credentials "true"

  # Set here the headers needed for the AJAX requests, if a needed header is not in this list you will see an error in Chrome mentioning which header needs to be added here
  Header set Access-Control-Allow-Headers "sender, filename, content-type, accept, x-requested-with, x-request"
</IfModule>
</IfModule>
于 2013-10-22T13:44:01.213 回答