使用Openresty中的lua将传递的URL参数提取到nginx.conf中。

我有一个名为'/gifts/'的 url,下面是管理逻辑的 nginx.conf 文件代码。

location /gifts {
    default_type text/html;
    set $target '';
    content_by_lua '
        local redis = require "resty.redis";
        local red = redis:new()
        red:set_timeout(1000) -- 1 sec
        local ok, err = red:connect("127.0.0.1", 6379)
        if not ok then
            ngx.log(ngx.ERR, err, "Redis failed to connect")
            return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        end
        local ok1, err = red:set("Animal", "DOG")
        if not ok then
            ngx.say("Failed to set cache in redis", err)
        end
        local res, err = red:get("Animal")
        if not res then
            ngx.say("Failure", err)
        end
        ngx.say("Animal", res)
';
}

对于 /gifts/,它对我来说正常工作。 但我有一个要求,我想在此登录中获取参数,例如 /gifts?key=name&value=Prashant 我想获取 key 和 value 的值。

点赞
用户1850358
用户1850358

我使用 req.get_uri_args() 函数来获取通过 URL 传递的所有参数。

local args = ngx.req.get_uri_args()
2013-11-15 10:34:06
用户1126127
用户1126127

请看ngx.req.get_uri_args(),它会返回一个 Lua 表格,其中包含当前请求 URL 查询参数。

例如:

 location = /test {
    content_by_lua '
        local args = ngx.req.get_uri_args()
        for key, val in pairs(args) do
            if type(val) == "table" then
                ngx.say(key, ": ", table.concat(val, ", "))
            else
                ngx.say(key, ": ", val)
            end
        end
    ';
}
2015-08-24 11:59:20