linux nginx 跨域的简单解决方案


直接在vhost的配置文件下,server内配置如下即可,不需要安装第三方nginx模块。

set $origin '*';
if ($http_origin) {
    set $origin "$http_origin";
}

add_header Access-Control-Allow-Credentials "false";
add_header Access-Control-Allow-Origin "$origin";
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'Origin,Access-Control-Request-Headers,Access-Control-Allow-Headers,DNT,X-Requested-With,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-M
odified-Since,Cache-Control,Content-Type,Accept,Connection,Cookie,X-XSRF-TOKEN,X-CSRF-TOKEN,Authorization';

主要提示是:

header in the response must not be the wildcard '*'

表示不能够使用通配符 Access-Control-Allow-Origin *
需要指定域,曲线救国定义一个rogin变量呗。

不能够指定跨域域名则cookie无效,其实前后端分离的项目,无需cookie直接设置 add_header Access-Control-Allow-Credentials "false";

之前我是用 more_set_headers 'access-control-allow-origin: *'; 的还需要安装more_set_headers模块,上面的简单用法,add_header是nginx的标配。


原文链接:https://blog.yongit.com/note/199778.html