编辑:我现在找到了更好的答案。
使用无服务器功能插件,可以使用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...
原答案:
您可以在路由定义中使用正则表达式和捕获组来将路径(或其一部分)保存在变量中:
^/old-api/(?<path>.*)$
遗憾的是,Response Transformer 不能像Request Transformer Pluginpath
那样简单地使用变量来创建标头(参见https://konghq.com/blog/url-rewriting-in-kong)。Location: https://other-domain.org/new-api/$(uri_captures.<path>)
如果您只想重定向一个 html 页面,您至少可以使用Request Termination Plugin和 set使路由响应代码 301 status_code=301
。您还可以返回text/html
mime-type 并返回
<script>location.href = 'https://other-domain.org/new-api/' + location.pathname.replace(/^\/old-api/, '/new-api')</script>
在体内规避这个限制。
另一种方法是自己实现一个 Kong 插件(除了一个非常基本的插件之外,我不知道现有的插件,https://github.com/domecloud/kong-plugin-redirect,它可能会被扩展)。
PS:我刚刚发现了另一个看起来更强大的有前途的插件,虽然我还没有测试它。