3 Copyright (C) 201-2018 ZTE, Inc. and others. All rights reserved. (ZTE)
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
19 local BasePlugin = require "plugins.base_plugin"
20 local msbConf = require('conf.msbinit')
21 local log_util = require('lib.utils.log_util')
22 local url_matcher = require "plugins.redirect-transformer.url_matcher"
23 local log = log_util.log
24 local url_match_msb_route = url_matcher.is_match_msb_route
25 local RedirectTransformerPluginHandler = BasePlugin:extend()
27 function RedirectTransformerPluginHandler:new()
28 RedirectTransformerPluginHandler.super.new(self, "redirect-transformer-plugin")
31 function RedirectTransformerPluginHandler:header_filter()
32 RedirectTransformerPluginHandler.super.header_filter(self)
33 local originloc = ngx.header.Location
36 log("origin location:",originloc)
37 local patten_conform,route_match = url_match_msb_route(originloc)
38 if not patten_conform then
39 log("redirect-transformer output:","The redirect address may be outside msb, do nothing temporarily.")
44 --if the redirect address can be forwarded by msb,then donot modify it's url
45 newloc = ngx.re.sub(originloc, "^(https|http)(.*)", ngx.var.scheme.."$2", "oi")
47 --if the redirect address can not be forwarded by msb,then try to modify it's url
48 local svc_pub_url = ngx.ctx.svc_pub_url
49 local svc_url = ngx.ctx.svc_url
50 if(svc_pub_url and svc_pub_url == "/") then
51 --replace $svc_url with ""
52 newloc = ngx.re.sub(originloc, "^(https|http)://([^/]+)"..svc_url, ngx.var.scheme.."://".."$2", "oi")
54 --replace $svc_url with $svc_pub_url
55 newloc = ngx.re.sub(originloc, "^(https|http)://([^/]+)"..svc_url, ngx.var.scheme.."://".."$2"..svc_pub_url, "oi")
58 -- replace the backend server with the host of msb
59 local last_peer = ngx.ctx.last_peer
61 local backend_ip = ngx.re.gsub(last_peer.ip, "\\.", "\\.", "o")
62 newloc = ngx.re.sub(newloc, "^(https://|http://)"..backend_ip..":"..last_peer.port, "$1"..ngx.var.host..":"..ngx.var.server_port, "o")
64 ngx.header["Location"] = newloc
65 log("redirect-transformer output:","replace the redirect address to :"..newloc)
66 ngx.log(ngx.WARN, "redirect-transformer replace the redirect address to:"..newloc, " origin location:",originloc)
70 return RedirectTransformerPluginHandler