Nginx Config for Cors - add_header directive is not allowed

前端 未结 3 1603
南笙
南笙 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:25

    The rule if in location can be bypassed by some tricks, so that you don't have to write/include CORS rules in every location block.

    server {
        set $cors_origin "";
        set $cors_cred   "";
        set $cors_header "";
        set $cors_method "";
    
        if ($http_origin ~* "^http.*\.yourhost\.com$") {
                set $cors_origin $http_origin;
                set $cors_cred   true;
                set $cors_header $http_access_control_request_headers;
                set $cors_method $http_access_control_request_method;
        }
    
        add_header Access-Control-Allow-Origin      $cors_origin;
        add_header Access-Control-Allow-Credentials $cors_cred;
        add_header Access-Control-Allow-Headers     $cors_header;
        add_header Access-Control-Allow-Methods     $cors_method;
    }
    

    This works because nginx will not return a header if its value is an empty string.

提交回复
热议问题