后端程序员之路 45、nginx CORS 跨域

在提供api给其它应用使用时,有时我们会要限制它的跨域使用,而有时,我们又要用CORS来打破AJAX只能同源使用的限制

跨域资源共享 CORS 详解 - 阮一峰的网络日志
http://www.ruanyifeng.com/blog/2016/04/cors.html

总结:
1、浏览器发出CORS请求,即在访问时http头里增加一个Origin字段
2、服务端判断Origin,然后在返回的http头里增加Access-Control-Allow-Origin、Access-Control-Allow-Credentials字段
3、JSONP只支持GET,CORS支持所有,但JSONP支持老浏览器,并且不需要服务端支持

Nginx通过CORS实现跨域 - OPEN 开发经验库
http://www.open-open.com/lib/view/open1472737324822.html

Nginx CORS实现JS跨域 - oyzl68的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/oyzl68/article/details/18741057

nginx允许所有二级域名跨域请求 - 曾健生的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/newjueqi/article/details/51385657

nginx配置文件里支持CORS很简单,但是如果支持多个指定网站,或者支持正则匹配,则有几种写法,以下我在用的一种:

map $http_origin $corsHost {
    default       0;
    "~http://a.a.cn" $http_origin;
    "~https://b.b.b.com" $http_origin;
    "~https?://(.*).c.com" $http_origin;
    }
server {
    ...
    add_header 'Access-Control-Allow-Origin' $corsHost;
    add_header Access-Control-Allow-Methods GET,POST;
    ...

原文地址:https://www.cnblogs.com/zapline/p/6772575.html