nginx-CORS跨域配置

前言

跨域资源限制是浏览器限制的,后端直接访问没有经过浏览器是可以访问的。

简单请求和非简单请求(预检请求)

  1. 简单的请求是不会触发CORS的预检的。简单请求必须是满足以下三个条件:

    • 请求方法:GET、HEAD、POST
    • 请求标头:Accept、Accept-Language、Content-Language
    • Content-Type:application/x-www-form-urlencoded、multipart/form-data、text/plain
  2. 非简单请求在发出真正请求前,浏览器会使用该OPTIONS方法向另一个源上的资源发送HTTP请求,以确定实际请求是否可以安全发送。只有在预检请求完成后,才发送真正的请求。

带凭据的请求

  1. 因为预检请求是不得包含凭据,所以服务端需要配置Access-Control-Allow-Credentials: true,表示可以使用凭据进行实际请求。
  2. Access-Control-Allow-Origin不能设置为*,需要指定明确的域名。
  3. Access-Control-Allow-Headers不能设置为*,需要指定明确的标头。
  4. Access-Control-Allow-Methods不能设置为*,需要指定明确的请求方法。

带凭据请求的nginx的配置示例

# 正则匹配对应的域名作为Access-Control-Allow-Origin的值
# 在http的层级下配置
http {
    map $http_origin $allow_origin {
        ~^https?://(.+\.com\.cn|localhost:\d\{1,5\})$ $http_origin;
        default '';
    }

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' $allow_origin;
        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';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    add_header 'Access-Control-Allow-Origin' $allow_origin;
    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';
    add_header 'Access-Control-Allow-Credentials' 'true';

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值