首页 > 解决方案 > Kong作为重定向服务

问题描述

是否可以在不修改模板的情况下在 KONG 中配置 HTTP 重定向规则(例如,如果请求匹配^/old-api/(.*)$模式则返回 301 到) (即使用 API 和某些插件设置此类规则)?https://other-domain.org/new-api/$1nginx.conf

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

标签: kongkong-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...

原答案

您可以在路由定义中使用正则表达式和捕获组来将路径(或其一部分)保存在变量中:

^/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/htmlmime-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:我刚刚发现了另一个看起来更强大的有前途的插件,虽然我还没有测试它。


推荐阅读