说说Access-Control-Allow-Origin

Access-Control-Allow-Origin,是W3C标准CORS在HTTP响应头中新增的一个字段。W3C对其的说明如下:

The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header, "*", or "null" in the response. ABNF:

Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"

In practice the origin-list-or-null production is more constrained. Rather than allowing a space-separated list of origins, it is either a single origin or the string "null".

上述说明的大致意思:Access-Control-Allow-Origin的值是请求头Origin字段的值、"*"、"null",然后是ABNF格式的定义,最后提示origin-list-or-null在产品实际中多用来做限制,不是一个空格分隔的origin的列表,而只能是单个origin或字符串"null"。

读懂了上述W3C的说明,就知道,为允许多个域名跨域访问,如下配置Nginx,都不可行。

add_header 'Access-Control-Allow-Origin' 'http://www.test.com http://user.test.com';
add_header 'Access-Control-Allow-Origin' 'http://www.test.com,http://user.test.com';
add_header 'Access-Control-Allow-Origin' 'http://www.test.com|http://user.test.com';

那么,怎么才能允许多域名跨域访问呢?

当然,如下配置Nginx,肯定可以。事实上,一些互联网公司,就是这么做的,甚至包括知名的互联网公司。

add_header 'Access-Control-Allow-Origin' '*';

使用"*",有人担心有安全问题,比如知乎上的提问

StackOverflow有人问到这样的问答,老外也给出了答案。被采用的回答,是针对Apache的,使用.htaccess,如下:

# ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
        SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    </IfModule>
</FilesMatch>

那么,如何配置Nginx呢?和Apache的配置思路类似,根据老外的回答,Nginx配置如下:

# allow origin list
set $ACAO 'http://www.test.com http://user.test.com';

# set single origin
if ($http_origin ~* ^https?://(www|user)\.test\.com$) {
    set $ACAO $http_origin;
}

add_header 'Access-Control-Allow-Origin' '$ACAO';

其实上面的set $ACAO 'http://www.test.com http://user.test.com';可有可无,这里建议保留,有以下好处:

  1. if ($http_origin ~* ^https?://(www|user)\.test\.com$) {里面的正则表达式可能会很复杂,保留origin list可以很直观的知道支持的域名
  2. 若ajax访问时,请求头的Origin字段不在origin list中,浏览器的控制台会打出类似如下的错误信息,由此可以知道,服务器支持的origin list,便于调试。
    XMLHttpRequest cannot load http://www.test.com/.
    The 'Access-Control-Allow-Origin' header contains multiple values 'http://www.test.com http://user.test.com', but only one is allowed.
    Origin 'http://junyi.me' is therefore not allowed access.

结合CORS on Nginx,写成Nginx配置片段enable-cors.conf,使用的时候,只需如下这样:

location / {
    ... other config ...
    include enable-cors.conf;
}

完整的enable-cors.conf配置片段如下:

#
# Wide-open CORS config for nginx
#

# allow origin list
set $ACAO 'http://www.test.com http://user.test.com';

# set single origin
if ($http_origin ~* ^https?://(www|user)\.test\.com$) {
    set $ACAO $http_origin;
}

if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '$ACAO';
    #
    # Om nom nom cookies
    #
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    #
    # Custom headers and headers various browsers *should* be OK with but aren't
    #
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    #
    # Tell client that this pre-flight info is valid for 20 days
    #
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}
if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' '$ACAO';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '$ACAO';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}