首页 > 解决方案 > 配置nginx发出后台请求

问题描述

我正在构建一个应用程序,我需要对 api-data 组合使用情况进行一些分析。下面是我的 nginx 配置 -

location /r/ {
    rewrite /r/(.*)$ http://localhost:3000/sample/route1/$1 redirect;
    post_action /aftersampleroute1/$1;
}
location /aftersampleroute1/ {
    rewrite /aftersampleroute1/(.*) /stats/$1;
    proxy_pass http://127.0.0.1:3000;
}

location/r/用于将浏览器请求重定向到使用 id执行某些操作的http://localhost:80/r/quwjDP4usapi 。现在在后台我想将 id 传递给 stats api ,它会更新该 id 的 db 记录。/sample/route1/quwjDP4usquwjDP4usquwjDP4us/stats/quwjDP4us

当我启动 nginx 并发出请求时,http://localhost:80/r/quwjDP4usnginx 成功地将我的请求重定向到我的应用程序,但没有在后台向 stats api 发出第二个请求。我错过了什么?

注意 -post_action不包含在 nginx 文档中,我可以使用备用模块/指令吗?

标签: nginxproxynginx-locationnginx-reverse-proxy

解决方案


正如您正确提到的那样,post_action没有记录,并且一直被认为是非官方指令。

Nginx 从 1.13.4 版本开始提供了一个新的“镜像”模块,在文档中进行描述。所以我建议你试一试。在你的情况下,它看起来像这样 -</p>

location /r/ {
    rewrite /r/(.*)$ http://localhost:3000/sample/route1/$1 redirect;
    mirror /stats;
}

location = /stats {
    internal;
    rewrite /sample/route1/(.*) /stats/$1;
    proxy_pass http://127.0.0.1:3000;
}

这行不通!

我已经建立了一个测试配置,不幸的是这不起作用。它既不适用rewrite也不适用return。但它适用于proxy_pass.

为什么

解释如下。HTTP 请求在 Nginx 中的处理过程中按顺序通过几个“阶段”。事情是mirror在阶段触发,该阶段PRECONNECT发生REWRITErewrite/return结束请求处理的阶段之后。因此,mirror甚至不会被触发,因为它的处理将在以后发生。

如果从该位置提供文件或通过proxy_pass(或fastcgi_pass,等)代理,处理将最终进入REWRITE阶段并被mirror执行。

阶段在此处的 Nginx 文档中进行了描述。

解决方法

如果没有权衡,我看不到任何好的解决方案。您可以创建一个额外的位置(返回重定向)并从 代理您的请求/r/,以便mirror触发。像这样,取决于您的其余配置:

location /r/ {
  # you may need setting Host to match `server_name` to make sure the
  # request will be caught by this `server`.
  # proxy_set_header Host $server_name;
  proxy_pass http://<ip from listen>:<port from listen>/redirect/;
  mirror /stats;
}

location = /redirect {
  rewrite /redirect(.*)$ http://localhost:3000/sample/route1$1 redirect;
}

当然,这是次优的,并且有额外的样板。


推荐阅读