Nginx Config for Cors - add_header directive is not allowed

前端 未结 3 1606
南笙
南笙 2021-02-03 22:52

I am trying add CORS directive to my nginx file for as simple static HTML site. (taken from here http://enable-cors.org/server_nginx.html)

Would there be a reason why it

3条回答
  •  清歌不尽
    2021-02-03 23:20

    add_header has to be placed under either http, server, location or if in location block.

    You are placing in under if in server. Move them under the location block.

    server {
    
    
        listen 8080;
    
        location / {
            root /var/www/vhosts/mysite;
    
            if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
                set $cors "true";
            }
    
            if ($request_method = 'OPTIONS') {
                set $cors "${cors}options";
            }
    
            if ($request_method = 'GET') {
                set $cors "${cors}get";
            }
            if ($request_method = 'POST') {
                set $cors "${cors}post";
            }
    
            if ($cors = "trueget") {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Credentials' 'true';
            }
    
            if ($cors = "truepost") {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Credentials' 'true';
            }
    
            if ($cors = "trueoptions") {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
                add_header 'Content-Length' 0;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                return 204;
            }
        }
    }
    

    Source: http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

提交回复
热议问题