Nginx解決跨域問題(CORS)
阿新 • • 發佈:2019-01-30
0x0前言
CORS(Cross-Origin Resource Sharing) 跨域資源共享,是一種允許當前域(domain)的資源(比如html/js/web service)被其他域(domain)的指令碼請求訪問的機制,通常由於同域安全策略(the same-origin security policy)瀏覽器會禁止這種跨域請求。
如:a.com 請求b.com的資源時,就涉及到了跨域。目前常見的跨域解決方案一般分為如下幾類:
- jsonp返回值解決get請求
- iframe解決跨域訪問
- Nginx 解決CORS
0x1 Nginx配置
0x1_1簡單配置:
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';
}
}
add_header:授權從a.com的請求
第二條add_header:當該標誌為真時,響應於該請求是否可以被暴露
第三條add_header:指定請求的方法,可以是GET,POST,PUT,DELETE,HEAD
同樣支援萬用字元,如允許來自任何域的請求:
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';
}
}
因為POST跨域請求會先發一次OPTIONS的嗅探請求,所有有的場景涉及到設定OPTIONS。
0x2 參考文獻
0x3關於我
- @Author:Zemo
- @Email:zemochen#126.com
- 歡迎轉載,讓更多的人學到東西