编辑:我现在找到了更好的答案。
使用Serverless function plugin,可以使用Location 标头进行正确的重定向。下面的 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>.*)$
遗憾的是,响应转换器不能像Request Transformer Plugin 那样简单地使用path 变量来创建Location: https://other-domain.org/new-api/$(uri_captures.<path>) 标头(参见https://konghq.com/blog/url-rewriting-in-kong)。
如果你只想重定向一个 html 页面,你至少可以通过使用Request Termination Plugin 并设置status_code=301 使路由响应代码 301。也可以返回text/htmlmime-type 并返回
<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 似乎更强大,虽然我还没有测试它。