Nignx实现跨域

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;
    location / {
            #支持其他请求
            add_header Access-Control-Allow-Methods PUT;
            #设置预检请求的缓存
            add_header Access-Control-Max-Age 3600;
            #允许Cookie
            add_header Access-Control-Allow-Credentials true;
            #这里最好做判断,怕麻烦的话就写*,但是不建议
            if ($http_origin = http://localhost){
                    add_header Access-Control-Allow-Origin http://localhost;
            }
            if ($http_origin = http://127.0.0.1){
                    add_header Access-Control-Allow-Origin http://127.0.0.1;
            }
            #为了方便,这样写了
            add_header Access-Control-Allow-Headers $http_access_control_request_headers;
            if ($request_method = OPTIONS){
                    return 200;
            }
    }
    error_page 404 /404.html;
        location = /40x.html {
    }
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}

评论

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1