Nginx跨域

2018-08-24  本文已影响0人  六弦极品

Nginx解决跨域问题(CORS)

CORS(Cross-Origin Resource Sharing) 跨域资源共享,是一种允许当前域(domain)的资源(比如html/js/web service)被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求。
如:a.com 请求b.com的资源时,就涉及到了跨域。目前常见的跨域解决方案一般分为如下几类:

Nginx配置

简单配置:

server {
        listen       80;
        server_name  b.com;
        location /{
            add_header 'Access-Control-Allow-Origin' 'http://a.com';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET';
        }
}
server {
        listen 80;
        server_name b.com;
        location /{
            Access-Control-Allow-Origin: *
        }
    }

0x1_2 高级配置

location / {
     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允许多个域名跨域

map $http_origin $other_domain{
    default '';
    "~http://aaa.bbb.com" http://aaa.bbb.com;
    "~http://ccc.ddd.com"  http://ccc.ddd.com;
}
server {
   .................
    location /uploads {
        add_header Access-Control-Allow-Origin $other_domain;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    .................
}
上一篇 下一篇

猜你喜欢

热点阅读