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>
但是这不起作用。
你们能帮助我吗?
答案 0 :(得分:5)
首选方法是读取请求标头,找到源,在服务器端代码中检查它。如果允许域访问该页面,请将原始域发送回一个Access-Control-Allow-Origin
标头。
另一个专家:没有其他域用户会看到允许的域名列表。每个用户只能看到自己的域名(如果允许)。
答案 1 :(得分: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>