昨天写了个地址重写的 Kong 自定义插件,跟大家分享下,话不多说,上代码
schema.lua
return {
no_consumer = true,
fields = {
regex = { type = "string" },
replacement = { type = "string" },
flag = {type = "string"},
},
self_check = function(schema, plugin_t, dao, is_update)
return true
end
}
handler.lua
local BasePlugin = require "kong.plugins.base_plugin"
local json = require("cjson")
local RewriteHandler = BasePlugin:extend()
local ngx = ngx
local kong = kong
RewriteHandler.PRIORITY = 2000
RewriteHandler.VERSION = "0.1.0"
function RewriteHandler:access(conf)
RewriteHandler.super.access(self)
local host = ngx.var.host
kong.log("Debug http-rewrite plugin, host is: ", host, " ,uri is: ", ngx.var.request_uri, " service is: ",service," ,config is: ", json.encode(conf))
kong.log("Debug http-rewrite plugin, regex is: ",regex, " replacement is : ",replacement)
local replace,n,err = ngx.re.sub(ngx.var.request_uri, conf.regex, conf.replacement)
if replace and n == 0 then
return
end
if err then
kong.log("Error http-rewrite plugin, ngx.re.sub err: ",err, " ,host is: ", host, " ,uri is: ",
ngx.var.request_uri, " ,config is: ", json.encode(conf))
return
end
kong.log("Debug http-rewrite plugin, replace is: ",replace)
if conf.flag == "redirect" then
ngx.redirect(replace,302)
elseif conf.flag == "permanent" then
ngx.redirect(replace,301)
end
end
function RewriteHandler:new()
RewriteHandler.super.new(self, "http-rewrite")
end
return RewriteHandler
效果如下:
开启该插件后,访问 http://dev.lyafei.com:8000/api/appmarket/app/appmarket/1.2/?service=/checkapp
被自动重定向到 http://dev.lyafei.com:8000/api/appstore/app/appmarket/1.2/?service=/checkapp
我按照帖子配置了以后参数不见了
后面的path 使用 /(.*)$
新的用$1来接住
你代码中的local replace,n,err = ngx.re.sub(ngx.var.request_uri, conf.regex, conf.replacement)我改成了local replace,n,err = ngx.re.sub(host, conf.regex, conf.replacement),然后https://nginx.test.tech就可以转成http://nginx.test.com 加上了你之前说的 可以识别到额path但是 host不生效了
方便加个好友么 qq加你了 好像还是有点小问题
我试一试
请问一个api或一个service需要配置多个路径转发应该怎么做?
service下可以新建多个route,利用route来匹配转发即可
谢谢回复!但多个route只能匹配service对应的upstream吧,如果跳转到多个地址呢?我理想的效果是,文中的插件能配置多个转发
你可能弄错了,upstream 对应的是 service 的负载均衡,跳转的是不同的服务器,service下的route,你可以通过HOSTS、PATHS这种路径区分去匹配来达到一个接口转发到不同的路径
好的,感谢!
6666