[nginx] CORS配置多域名

如下

server {
    listen       80;
    server_name  www.your.com;
    root         /data/web/www.your.com;
    access_log   /var/log/nginx/www.your.com_access.log;
    error_log    /var/log/nginx/www.your.com_error.log;

    set $cors_origin "";
    if ( $http_origin ~ https?://.*\.(a|b)\.com ) {
        set $cors_origin $http_origin;
    }
    add_header Access-Control-Allow-Origin $cors_origin;
}

  curl测试跨域是否生效,a.jpg要存在,查看Access-Control-Allow-Origin字段。

[root@HD1g-static-website /usr/local/nginx/conf/conf.d]# curl -I -H "Origin: https://test.a.com" https://www.your.com/a.jpg
HTTP/1.1 200 OK
Date: Sun, 05 May 2019 06:12:53 GMT
Content-Type: image/jpeg
Content-Length: 134100
Connection: keep-alive
Last-Modified: Tue, 05 Mar 2019 07:01:43 GMT
ETag: "5c7e1ed7-20bd4"
Expires: Tue, 04 Jun 2019 06:12:53 GMT
Cache-Control: max-age=2592000
Access-Control-Allow-Origin: https://test.a.com
Accept-Ranges: bytes

  一个较完整的CORS,引用自https://enable-cors.org/server_nginx.html

[root@HD1g-static-website /usr/local/nginx/conf/conf.d]# cat nginx_cors 
if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    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' '*';
    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' '*';
    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';
}

 

posted @ 2019-05-05 14:25  金枪语  阅读(1097)  评论(0编辑  收藏  举报