ngx_lua_API 指令详解(四)ngx.exec指令

https://github.com/openresty/lua-nginx-module#ngxexec

参照:http://blog.csdn.net/weiyuefei/article/details/38434797

在Nginx中实现重定向可以通过rewrite指令,具体可参考《Nginx学习——http_rewrite_module的rewrite指令

通过Lua模块也可以实现同样的功能,Lua模块提供了相关的API来实现重定向的功能,

语法:

syntax: ngx.exec(uri, args?)

context: rewrite_by_lua*, access_by_lua*, content_by_lua*

1、主要实现的是内部的重定向,等价于下面的rewrite指令 rewrite regrex replacement last;

复制代码
     location /foo {
         content_by_lua_block {
             ngx.exec("/bar", "a=goodbye");
         }
     }

     location /bar {
         content_by_lua_block {
             local args = ngx.req.get_uri_args()
             for key, val in pairs(args) do
                 if key == "a" then
                     ngx.say(val)
                 end
             end
         }
     }
复制代码

curl http://192.168.18.180:8088/foo 输出为 goodbye

2、 args参数可以以string的形式给出,也可以以lua table的形式给出,如下所示: 

复制代码
     location /foo {
         content_by_lua_block {
             ngx.exec("/bar", { a= 4, b="hello world"});
         }
     }

     location /bar {
         content_by_lua_block {
             local args = ngx.req.get_uri_args()
             for key, val in pairs(args) do
                ngx.say(key.." = "..val)
             end
         }
     }
复制代码

3. 该方法不会主动返回,因此,强烈建议在调用该方法时,最好显示加上return,如下所示:

return ngx.exec(...)

 

posted @   Tinywan  阅读(12016)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示