nginx - 配置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/quwjDP4us
api 。现在在后台我想将 id 传递给 stats api ,它会更新该 id 的 db 记录。/sample/route1/quwjDP4us
quwjDP4us
quwjDP4us
/stats/quwjDP4us
当我启动 nginx 并发出请求时,http://localhost:80/r/quwjDP4us
nginx 成功地将我的请求重定向到我的应用程序,但没有在后台向 stats api 发出第二个请求。我错过了什么?
注意 -post_action
不包含在 nginx 文档中,我可以使用备用模块/指令吗?
解决方案
正如您正确提到的那样,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
发生REWRITE
在rewrite
/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;
}
当然,这是次优的,并且有额外的样板。
推荐阅读
- linux - mariadb 卸载但不干净
- react-native - 在 react-native 中降级 firebase sdk npm 包的问题
- javascript - 如何使用javascript中的特定键将两个字符串数组转换为对象数组,如键和值?
- powershell - PowerShell - 使用 foreach 和 compare-object 枚举 2 组 CSV 以输出差异
- javascript - 打开图形在单页应用程序 AngularJs 中无法正常工作
- javascript - 如何使用 Javascript 将点击事件保存到 HTML 表单
- javascript - Visualforce 中的 Javascript 和图像呈现为 Word
- vb.net - 是否有更改 datagridview 单元格值的功能?
- git - Eclipse - Git 提交和推送空文件夹
- javascript - 使用javascript更改div的背景图像