0

I have the following in nginx.conf:

header_filter_by_lua_block {
    ngx.header["Access-Control-Allow-Origin"] = "http://example.com"
}

I want to add another http://example.dev to the Access-Control-Allow-Origin. I tried doing http://example.com, http://example.dev but it didn't work.

I also tried doing:

if ($http_origin ~* "^http?://(example.com|example.dev)$") {
    add_header Access-Control-Allow-Origin "$http_origin";
}

But this made some issue in OPTIONS request so I really can't use this. Is there any other way to do inside header_filter_by_lua_block? Please help.

Damon
  • 1,034
  • 5
  • 23
  • 56

1 Answers1

3

Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you would like to allow, and if it matches, echo the value of the Origin header back to the client as the Access-Control-Allow-Origin header in the response.

(source)

So following code should solve your problem.

header_filter_by_lua_block {
  local origins = {
    ["http://example.com"] = true,
    ["http://example.dev"] = true
  }
  local origin = ngx.req.get_headers()["Origin"]  -- get request origin

  ngx.header["Access-Control-Allow-Origin"] = origins[origin] and origin or nil
}
csaar
  • 392
  • 2
  • 13