【问题标题】:Nginx proxy_pass changes behavior when defining the target in a variableNginx proxy_pass 在变量中定义目标时改变行为
【发布时间】:2020-10-13 09:51:35
【问题描述】:

我正在使用 nginx 对 AWS API Gateway 阶段进行反向代理。这很简单:

location /api {
    proxy_pass https://xxxxxxxxxx.execute-api.eu-central-1.amazonaws.com:443/production;
    proxy_ssl_server_name on;
}

但是,当 xxxxxxxxxx.execute-api.eu-central-1.amazonaws.com 的 DNS 条目发生变化时,这种方法会使 nginx 在上游服务过时,因为它会在启动时解析该条目。

在这篇文章之后:https://www.nginx.com/blog/dns-service-discovery-nginx-plus/ 我现在正在尝试在这样的变量中定义我的代理目标:

location /api {
    set $apigateway xxxxxxxxxx.execute-api.eu-central-1.amazonaws.com/production;
    proxy_pass https://$apigateway:443/;
    proxy_ssl_server_name on;
}

这将使 API Gateway 以 ForbiddenException: Forbidden 响应将通过先前设置而不使用变量的请求。阅读本文档:https://aws.amazon.com/de/premiumsupport/knowledge-center/api-gateway-troubleshoot-403-forbidden/ 它告诉我这可能是 WAF 过滤我的请求(当该 API 未启用 WAF 时),也可能是私有 API 缺少主机标头(当 API 是公共时)。

我想我可能做错了一件事情:

  1. 用于设置变量的语法错误
  2. 使用该变量会使 nginx 向 API Gateway 发送不同的标头,我需要手动干预。我确实尝试过设置 Host 标头,但没有任何区别。

使用的nginx版本是1.17.3

【问题讨论】:

  • 我认为该问题与this nginx ticketthis commit 有关。本质上,如果您使用带有 proxy_pass 的变量,那么它将忽略尾部反斜杠的行为。解决它的唯一方法似乎是使用像接受的答案一样的 URL 重写。

标签: nginx aws-api-gateway


【解决方案1】:

您在变量中嵌入了 URI /production,因此 :443 被标记在 URI 的末尾而不是主机名上。我不相信您需要:443,它是https 的默认端口。

此外,当在 proxy_pass 中使用变量并且在指令中指定了 URI 时,它会按原样传递给服务器,替换原始请求 URI。详情请见this document

您应该使用rewrite...break 更改URI 并从proxy_pass 语句中删除任何可选的URI。

例如:

location /api {
    set $apigateway xxxxxxxxxx.execute-api.eu-central-1.amazonaws.com;
    rewrite ^/api(.*)$ /production$1 break;
    proxy_pass https://$apigateway;
    proxy_ssl_server_name on;
}

此外,您需要在配置中的某处使用 resolver 语句。

【讨论】:

  • “我不相信你需要 :443”——我也不完全理解为什么,但 API Gateway 不会回答,除非我这样指定端口。手动重写并省略 proxy_pass 指令中的路径效果很好,谢谢。
【解决方案2】:

这似乎是 WAF 的误报。您是否尝试禁用 AWS WAF https://docs.aws.amazon.com/waf/latest/developerguide/remove-protection.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多