[nginx] CORS配置多域名

Posted hjfeng1988

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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字段。

[[email protected] /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,引用下次再补

[[email protected] /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‘;
}

  

  

以上是关于[nginx] CORS配置多域名的主要内容,如果未能解决你的问题,请参考以下文章

CORS(跨站资源共享)介绍

Nginx使用“逻辑与”配置origin限制,修复CORS跨域漏洞

linux学习:Nginx--常见功能配置片段与优化-06

AngularJS + Nginx CORS

Nginx通过CORS实现跨域(转)

Nginx解决跨域问题(CORS)