NgInx 作为 Kong 的反向代理

NgInx as reverse proxy with Kong

我想使用 Kong 作为我的 API 网关,运行 在 Docker 容器中。每个请求必须首先通过 NgInx 服务器,如果请求的 uri 匹配 example.com/api 它必须导致 api,在 Kong 中注册。

为了实现这一点,我使用以下命令将 API 添加到 Kong 中:

curl -i -X POST --url ipnumber:8001/apis -d 'name=my-api' -d `enter code here`'upstream_url=http://httpbin.org' -d 'hosts=example.com' -d 'uris=/api/my-api'

通过执行以下命令我得到了正确的答案,所以我认为 Kong 工作正常。

curl -i -X GET --url ipnumber:8000/api/my-api --header 'Host: example.com'

我的 NgInx 配置如下所示:

upstream kong {
  server 127.0.0.1:8000;
}

location /api {
   proxy_pass: http://kong;
}

在我的主机文件中,我已将 NgInx 服务器的 IP 配置为域名 example.com。

问题是:当我浏览到 example.com/api/my-api 甚至 example.com/my-api 时,结果是 NgInx 的 404 错误页面。

当我浏览到 ipnumber:8000/api/my-api 时,它会显示 Kong 的一条消息,说没有 api 匹配给定的值,这是正确的,因为主机名不是 example.com

我已经关注这个问题很长时间了,但一直无法解决。我也在寻找 https://getkong.org/docs/0.10.x/configuration/#custom-nginx-configuration-embedding-kong 但我不确定是否必须这样做,因为我已经有了自己的 nginx 配置。

提前感谢您的反馈。

您需要告诉 NGINX 将主机 header 上游转发给 Kong。您可以像这样使用 proxy_set_header 来做到这一点:

location /api {
   proxy_pass: http://kong;
   proxy_set_header Host $host;
}