kong - Kong作为重定向服务
问题描述
是否可以在不修改模板的情况下在 KONG 中配置 HTTP 重定向规则(例如,如果请求匹配^/old-api/(.*)$
模式则返回 301 到) (即使用 API 和某些插件设置此类规则)?https://other-domain.org/new-api/$1
nginx.conf
我想要实现的是 nginx 等效于带有或标志的rewrite
指令:http: //nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewriteredirect
permanent
解决方案
编辑:我现在找到了更好的答案。
使用无服务器功能插件,可以使用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:我刚刚发现了另一个看起来更强大的有前途的插件,虽然我还没有测试它。
推荐阅读
- angular - 如何在primeng表的paginator-bottom手动设置当前页码?
- asp.net-mvc - 在移动应用程序中保持应用程序始终打开
- javascript - 如何从父组件中设置 React Table 选定的行?
- flutter - Flutter GetX 更改主题需要热重载?
- javascript - 将对象推入数组 React Hooks
- java-11 - org.apache.catalina.LifecycleException:java.lang.VerifyError:操作数堆栈上的错误类型:ObjectMapper
- javascript - 如何在页面加载时使用views.py的上下文填充表格行?
- python - 即使安装了 python 3.9,也无法从命令提示符运行 python 程序
- xslt - XSLT Xp20 中的日期时间解析
- android - 单击按钮后从可组合函数返回一个值