码迷,mamicode.com
首页 > 其他好文 > 详细

[nginx] CORS配置多域名

时间:2019-05-05 14:39:14      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:eth   ash   type   website   ade   custom   nginx   oca   connect   

如下

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,引用下次再补

[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‘;
}

  

  

[nginx] CORS配置多域名

标签:eth   ash   type   website   ade   custom   nginx   oca   connect   

原文地址:https://www.cnblogs.com/hjfeng1988/p/10812838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!