Nginx Controller
添加全局性CORS
支持,需要自定义插件并且加载至nginx
中
内容目录
- 编写
CORS
脚本 - 创建
ConfigMap
对象 - 修改
nginx
全局配置ConfigMap
编辑CORS LUA
脚本
注意:
- 在添加允许跨域域名时特殊字符使用
%
转义 lua
文件命名必须是main.lua
local _M = {}
local originHeaderName = "OPTIONS"
local corsDomains = {
".*%.172%.20%..*",
".*%.192%.168%..*",
".*%.localhost.*"
}
local function setCorsHeader(originHeader)
ngx.header["Access-Control-Allow-Origin"] = originHeader
ngx.header["Access-Control-Allow-Credentials"] = "true"
ngx.header["Access-Control-Allow-Headers"] =
"ETag,Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,Content-Disposition,x-puat,x-test"
ngx.header["Access-Control-Expose-Headers"] = "Content-Disposition,x-permission-msg"
ngx.header["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS,HEAD,PUT"
end
function _M.rewrite()
if ngx.req.get_method() ~= originHeaderName then
return
end
setCorsHeader(ngx.req.get_headers()["Origin"])
return ngx.exit(ngx.HTTP_NO_CONTENT)
end
local function matchOrigin(originHeader)
for _, domain in ipairs(corsDomains) do
if string.match(originHeader, domain, 1) then
return true
end
end
return false
end
function _M.header_filter()
if ngx.req.get_method() == originHeaderName then
return
end
local httpOrigin = ngx.req.get_headers()["Origin"]
if not httpOrigin then
return
end
if matchOrigin(httpOrigin) then
setCorsHeader(httpOrigin)
end
end
return _M
使用插件
创建插件ConfigMap
对象
# kubectl create cm core-plugin-lua --from-file=main.lua
Nginx Controller
挂载插件
volumeMounts:
- mountPath: /etc/nginx/lua/plugins/cors/
name: cors-plugin-lua-cm
volumes:
- configMap:
name: cors-plugin-lua-cm
name: cors-plugin-lua-cm
修改Nginx Controller
全局配置ConfigMap
plugins
名称与挂载插件目录名称一致
data:
plugins: cors