nginx配置CORS 支持options请求

    add_header 'Access-Control-Allow-Methods' 'GET, POST,DELETE,PUT,CREATE, OPTIONS';
    if ($request_method = 'POST'){
                    add_header 'Access-Control-Allow-Origin' $http_origin;
                    add_header 'Access-Control-Allow-Credentials' 'true';
                    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,token,X-Requested-With,token,If-Modified-Since,Cache-Control,Content-Type,Range';
    }
        if ($request_method = 'GET'){
                        add_header 'Access-Control-Allow-Origin' $http_origin;
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,token,X-Requested-With,token,If-Modified-Since,Cache-Control,Content-Type,Range';
        }
                        
        if ($request_method = 'OPTIONS') {
                    add_header 'Access-Control-Allow-Origin' $http_origin;
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,token,X-Requested-With,token,If-Modified-Since,Cache-Control,Content-Type,Range';
                        add_header 'Access-Control-Max-Age' 1728000;
                        add_header 'Content-Type' 'text/plain; charset=utf-8';
                        add_header 'Content-Length' 0;
                        add_header 'Access-Control-Allow-Credentials' 'true';
                        return 204;
    }

以上配置是直接允许跨域服务器,并且增加了OPTIONS请求头,设置了请求头的缓存期,有效加速客户端请求速度。

摄影爱好者,全栈工程师,游戏玩家,积木苦手,超穷手办收藏爱好者

发表评论