How to set the value of the Access-Control-Allow-Origin header based on a list of allowed origins?

前端 未结 1 1697
生来不讨喜
生来不讨喜 2020-12-22 09:54

I have read quite a lot of posts but none of them worked though.

I have ec2 setup in aws installed with ubuntu 16.04 and nginx. went into the site-available

相关标签:
1条回答
  • 2020-12-22 10:18

    You can conditionally cause the Access-Control-Allow-Origin response header to be sent, with the right value, by adding something like the following to your nginx config.

    location / {
      set $is_allowed_origin "";
      if ($http_origin = "https://some.allowed.origin") {
        set $is_allowed_origin "true";
      }
      if ($http_origin = "https://another.allowed.origin") {
        set $is_allowed_origin "true";
      }
      if ($is_allowed_origin = "true") {
        add_header "Access-Control-Allow-Origin" "$http_origin";
      }
    }
    

    That’ll cause Access-Control-Allow-Origin: https://some.allowed.origin to be sent if the value of the Origin request header in the request is https://some.allowed.origin, and will cause Access-Control-Allow-Origin: https://another.allowed.origin to be sent if the Origin is https://another.allowed.origin, etc.

    And if the value of the Origin request header is neither https://some.allowed.origin or https://another.allowed.origin, then no Access-Control-Allow-Origin would be sent.

    0 讨论(0)
提交回复
热议问题