配置 nginx 发出后台请求

Joh*_*Doe 5 proxy nginx nginx-location nginx-reverse-proxy

我正在构建一个应用程序,需要对 api-数据组合使用情况进行一些分析。下面是我的 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ale*_*rov 6

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

\n\n

Nginx 从 1.13.4 版本开始提供了一个新的“镜像”模块,描述如下文档中所以我建议你尝试一下。在你的情况下,它看起来像这样 \xe2\x80\x93

\n\n
location /r/ {\n    rewrite /r/(.*)$ http://localhost:3000/sample/route1/$1 redirect;\n    mirror /stats;\n}\n\nlocation = /stats {\n    internal;\n    rewrite /sample/route1/(.*) /stats/$1;\n    proxy_pass http://127.0.0.1:3000;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是行不通的!

\n\n

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

\n\n

为什么

\n\n

解释如下。HTTP 请求在 Nginx 中处理期间会依次经过几个“阶段”。问题是,它是在晚于/结束请求处理的mirror阶段触发的。所以,PRECONNECTREWRITErewritereturnmirror甚至不会被触发,因为它的处理会稍后发生。

\n\n

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

\n\n

Nginx 文档中描述了各个阶段

\n\n

解决方法

\n\n

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

\n\n
location /r/ {\n  # you may need setting Host to match `server_name` to make sure the\n  # request will be caught by this `server`.\n  # proxy_set_header Host $server_name;\n  proxy_pass http://<ip from listen>:<port from listen>/redirect/;\n  mirror /stats;\n}\n\nlocation = /redirect {\n  rewrite /redirect(.*)$ http://localhost:3000/sample/route1$1 redirect;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

当然,这不是最理想的,并且有额外的样板。

\n