0

How should I get the part that's matched by a regex location in OpenResty / Nginx Lua module?

For example, I want to use $1 in Lua in the following case:

location ~ ^/example/([0-9]+)/ {
  content_by_lua_block {
    -- What to use for \1 ?
    ngx.say("Code: " .. (ngx.var.1 + 1))
  }
}

The expected behavior would be getting Code: 1235 when visiting /example/1234/.

1 Answer 1

3

Replace ngx.var.1 with ngx.var[1]

From Lua reference manual:

The syntax var.Name is just syntactic sugar for var["Name"]

However, it only works with string keys.

From OpenResty manual:

Nginx regex group capturing variables $1, $2, $3, and etc, can be read by this interface as well, by writing ngx.var[1], ngx.var[2], ngx.var[3], and etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.