我正在尝试为所有子域,端口和协议启用CORS。

例如,我希望能够从http://sub.mywebsite.example:8080/到https://www.mywebsite.example/*运行XHR请求

通常情况下,我想启用来自源匹配的请求(并且仅限于):

/ / * .mywebsite.example: * / *


当前回答

在我的例子中使用的是angular

在我的HTTP拦截器,我设置

with Credentials: true.

在请求头中

其他回答

当在.htaccess中设置Access-Control-Allow-Origin时,只有以下几种有效:

SetEnvIf Origin "http(s)?://(.+\.)?domain\.example(:\d{1,5})?$" CRS=$0
Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS

我尝试了其他几个建议的关键字头追加,头集,没有工作建议在Stack Overflow上的许多答案,虽然我不知道这些关键字是否过时或对nginx无效。

以下是我的完整解决方案:

SetEnvIf Origin "http(s)?://(.+\.)?domain\.example(:\d{1,5})?$" CRS=$0
Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS
Header merge Vary "Origin"

Header always set Access-Control-Allow-Methods "GET, POST"
Header always set Access-Control-Allow-Headers: *

# Cached for a day
Header always set Access-Control-Max-Age: 86400

RewriteEngine On

# Respond with 200OK for OPTIONS
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

当从“cookie域”(www.domain.example)读取字体时,我们在静态的“无cookie”域上也遇到了类似的问题,这篇文章是我们的英雄。看这里:我如何修复“丢失跨源资源共享(CORS)响应头”webfont问题?

对于复制/粘贴-r类型(并给一些道具),我从所有的贡献中拼凑起来,并将其添加到站点根目录的。htaccess文件的顶部:

<IfModule mod_headers.c>
 <IfModule mod_rewrite.c>
    SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.example|mywebsite\.example)(:\d{1,5})?$" CORS=$0
    Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
    Header merge  Vary "Origin"
 </IfModule>
</IfModule>

超级安全,超级优雅。喜欢它:你不必开放你的服务器带宽给资源小偷/热链接者类型。

我需要一个只有php的解决方案,所以以防有人也需要它。它接受一个允许的输入字符串,如“*.example.com”,如果输入匹配,则返回请求头服务器名。

function getCORSHeaderOrigin($allowed, $input)
{
    if ($allowed == '*') {
        return '*';
    }

    $allowed = preg_quote($allowed, '/');

    if (($wildcardPos = strpos($allowed, '*')) !== false) {
        $allowed = str_replace('*', '(.*)', $allowed);
    }

    $regexp = '/^' . $allowed . '$/';

    if (!preg_match($regexp, $input, $matches)) {
        return 'none';
    }

    return $input;
}

下面是phpunit数据提供程序的测试用例:

//    <description>                            <allowed>          <input>                   <expected>
array('Allow Subdomain',                       'www.example.com', 'www.example.com',        'www.example.com'),
array('Disallow wrong Subdomain',              'www.example.com', 'ws.example.com',         'none'),
array('Allow All',                             '*',               'ws.example.com',         '*'),
array('Allow Subdomain Wildcard',              '*.example.com',   'ws.example.com',         'ws.example.com'),
array('Disallow Wrong Subdomain no Wildcard',  '*.example.com',   'example.com',            'none'),
array('Allow Double Subdomain for Wildcard',   '*.example.com',   'a.b.example.com',        'a.b.example.com'),
array('Don\'t fall for incorrect position',    '*.example.com',   'a.example.com.evil.com', 'none'),
array('Allow Subdomain in the middle',         'a.*.example.com', 'a.bc.example.com',       'a.bc.example.com'),
array('Disallow wrong Subdomain',              'a.*.example.com', 'b.bc.example.com',       'none'),
array('Correctly handle dots in allowed',      'example.com',     'exampleXcom',            'none'),

对于Spring,你应该使用allowedOriginPatterns,它完全是你想要的

setAllowedOrigins(java.util.List<java.lang.String>)的替代方案,除了端口列表外,还支持在主机名中的任何位置使用“*”的更灵活的起源模式。例子:

https://*.domain1.com -- domains ending with domain1.com
https://*.domain1.com:[8080,8081] -- domains ending with domain1.com on port 8080 or port 8081
https://*.domain1.com:[*] -- domains ending with domain1.com on any port, including the default port 

与只支持""而不能与allowCredentials一起使用的allowedOrigins相反,当一个allowedOriginPattern被匹配时,Access-Control-Allow-Origin响应头被设置为匹配的原点,而不是""或模式。因此,allowedOriginPatterns可以与setAllowCredentials(java.lang.Boolean)设置为true结合使用。

例如:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            List<String> allowedOrigins = List.of("https://*.example.com", "http://*.example2.com[80,8080]");
            registry.addMapping("/**").allowedOriginPatterns(allowedOrigins.toArray(new String[0]));

        }
    };
}

看起来最初的答案是在Apache 2.4之前。这对我没用。下面是我为了让它在2.4中正常工作所做的修改。这将适用于你公司的任何深度的子域。

SetEnvIf Host ^((?:.+\.)*yourcompany\.example?)$    CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{REQUEST_SCHEME}e://%{CORS_ALLOW_ORIGIN}e    env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"