前言
CORS(Cross-Origin Resource Sharing)
跨域資源共享,是一種允許當(dāng)前域(domain)的資源(比如html/js/web
service)被其他域(domain)的腳本請(qǐng)求訪問的機(jī)制,,通常由于同域安全策略(the same-origin security
policy)瀏覽器會(huì)禁止這種跨域請(qǐng)求。
如:a.com 請(qǐng)求b.com的資源時(shí),,就涉及到了跨域,。目前常見的跨域解決方案一般分為如下幾類:
- jsonp返回值解決get請(qǐng)求
- iframe解決跨域訪問
- Nginx 解決CORS
Nginx配置
1 簡單配置
-
add_header:授權(quán)從a.com的請(qǐng)求
-
第二條add_header:當(dāng)該標(biāo)志為真時(shí),,響應(yīng)于該請(qǐng)求是否可以被暴露
-
第三條add_header:指定請(qǐng)求的方法,可以是GET,,POST,,PUT,DELETE,,HEAD
同樣支持通配符,,如允許來自任何域的請(qǐng)求:

2 高級(jí)配置
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';
}
}
因?yàn)镻OST跨域請(qǐng)求會(huì)先發(fā)一次OPTIONS的嗅探請(qǐng)求,所有有的場(chǎng)景涉及到設(shè)置OPTIONS,。