in apisix/plugins/redirect.lua [181:261]
function _M.rewrite(conf, ctx)
core.log.info("plugin rewrite phase, conf: ", core.json.delay_encode(conf))
local ret_code = conf.ret_code
local attr = plugin.plugin_attr(plugin_name)
local ret_port = get_port(attr)
local uri = conf.uri
local regex_uri = conf.regex_uri
local proxy_proto = core.request.header(ctx, "X-Forwarded-Proto")
local _scheme = proxy_proto or core.request.get_scheme(ctx)
if conf.http_to_https and _scheme == "http" then
if ret_port == nil or ret_port == 443 or ret_port <= 0 or ret_port > 65535 then
uri = "https://$host$request_uri"
else
uri = "https://$host:" .. ret_port .. "$request_uri"
end
local method_name = ngx.req.get_method()
if method_name == "GET" or method_name == "HEAD" then
ret_code = 301
else
ret_code = 308
end
end
if ret_code then
local new_uri
if uri then
local err
new_uri, err = concat_new_uri(uri, ctx)
if not new_uri then
core.log.error("failed to generate new uri by: " .. uri .. err)
return 500
end
elseif regex_uri then
local n, err
new_uri, n, err = re_sub(ctx.var.uri, regex_uri[1],
regex_uri[2], "jo")
if not new_uri then
local msg = string_format("failed to substitute the uri:%s (%s) with %s, error:%s",
ctx.var.uri, regex_uri[1], regex_uri[2], err)
core.log.error(msg)
return 500
end
if n < 1 then
return
end
end
if not new_uri then
return
end
local index = str_find(new_uri, "?")
if conf.encode_uri then
if index then
new_uri = core.utils.uri_safe_encode(str_sub(new_uri, 1, index-1)) ..
str_sub(new_uri, index)
else
new_uri = core.utils.uri_safe_encode(new_uri)
end
end
if conf.append_query_string and ctx.var.is_args == "?" then
if index then
new_uri = new_uri .. "&" .. (ctx.var.args or "")
else
new_uri = new_uri .. "?" .. (ctx.var.args or "")
end
end
core.response.set_header("Location", new_uri)
return ret_code
end
end