如何在 lua openresty nginx 中添加多个源?
How to add multiple origins in lua openresty nginx?
我在 nginx.conf
中有以下内容:
header_filter_by_lua_block {
ngx.header["Access-Control-Allow-Origin"] = "http://example.com"
}
我想在 Access-Control-Allow-Origin
中再添加一个 http://example.dev
。我试过 http://example.com, http://example.dev
但没用。
我也试过:
if ($http_origin ~* "^http?://(example.com|example.dev)$") {
add_header Access-Control-Allow-Origin "$http_origin";
}
但这在 OPTIONS
请求中造成了一些问题,所以我真的不能使用它。在header_filter_by_lua_block
里面有没有其他的办法呢?请帮忙。
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)
所以下面的代码应该可以解决你的问题。
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
}
我在 nginx.conf
中有以下内容:
header_filter_by_lua_block {
ngx.header["Access-Control-Allow-Origin"] = "http://example.com"
}
我想在 Access-Control-Allow-Origin
中再添加一个 http://example.dev
。我试过 http://example.com, http://example.dev
但没用。
我也试过:
if ($http_origin ~* "^http?://(example.com|example.dev)$") {
add_header Access-Control-Allow-Origin "$http_origin";
}
但这在 OPTIONS
请求中造成了一些问题,所以我真的不能使用它。在header_filter_by_lua_block
里面有没有其他的办法呢?请帮忙。
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)
所以下面的代码应该可以解决你的问题。
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
}