Skip to content

Instantly share code, notes, and snippets.

@Yxnt
Last active December 11, 2017 05:20
Show Gist options
  • Save Yxnt/481ac7054d870b5b42d37f298f50771c to your computer and use it in GitHub Desktop.
Save Yxnt/481ac7054d870b5b42d37f298f50771c to your computer and use it in GitHub Desktop.
多域名跨域处理
local function set_cross_domain_name()
local domain = "xxx.com" -- replace this
local domain_reg = string.format(".*%s",domain)
local schema = ngx.var.scheme -- get schema
local server_name = ngx.var.server_name -- get request header server name
local origin_name = ngx.req.get_headers()['Origin'] -- get request header Origin value
local m_server,err = ngx.re.match(server_name,domain_reg,"iu") -- match domain value from request server name
if origin_name then
local m_origin,err = ngx.re.match(origin_name,domain_reg,"iu") -- match domain value from request Origin
if m_origin then
return origin_name
end
elseif m_server then
local domain = string.format("%s://%s", schema,server_name)
return domain
end
end
local http_method = ngx.req.get_method() -- get http request method
ngx.header["Access-Control-Allow-Origin"] = set_cross_domain_name() -- add cross domain headers
if http_method == "OPTIONS" then -- method is OPTIONS
return ngx.exit(ngx.HTTP_OK) -- set http status code
end
server {
server_name abc.xxx.com;
listen 80;
access_by_lua_file cross_domain.lua; # set cross_domain file
location / {
proxy_pass http://xxx;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment