Kong 作为重定向服务

Kong as redirection service

是否可以在不修改 nginx.conf 模板(即使用 API 和一些插件设置此类规则)?

我想要实现的是 nginx 等效于带有 redirectpermanent 标志的 rewrite 指令:http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

编辑:我现在找到了更好的答案。

使用 Serverless function plugin,可以使用 Location header 进行正确的重定向。以下 Lua 代码应该这样做:

kong.response.exit(301, 'page moved - redirecting...', {['Location'] = 'https://other-domain.org/' .. kong.request.get_path_with_query():gsub("%/old-api/", "/new-api/")})

之后,响应如下所示:

# curl -i http://original-domain.org/old-api/abc
HTTP/2 301
date: Sat, 09 Jan 2021 17:03:04 GMT
location: https://other-domain.org/new-api/abc
content-length: 28
x-kong-response-latency: 7

page moved - redirecting...

原答案:

您可以在路由定义中使用正则表达式和 capturing groups 将路径(或部分路径)保存在变量中:

^/old-api/(?<path>.*)$

遗憾的是,Response Transformer 不能简单地使用 path 变量来创建 Location: https://other-domain.org/new-api/$(uri_captures.<path>) header,如 Request Transformer Plugin can (see https://konghq.com/blog/url-rewriting-in-kong).

如果您只想重定向 html 页面,您至少可以使用 Request Termination Plugin 和设置 status_code=301 使路由以代码 301 响应。您还可以 return text/html mime-type 和 return

<script>location.href = 'https://other-domain.org/new-api/' + location.pathname.replace(/^\/old-api/, '/new-api')</script>

在body中规避这个限制。

另一种方法是自己实现一个 Kong 插件(除了一个非常基本的 https://github.com/domecloud/kong-plugin-redirect,我不知道现有的插件,它可能会被扩展)。

PS: 刚发现another promising plugin好像更厉害,虽然我还没有测试