user9099802
user9099802

Reputation: 253

Use variable in lua and nginx

I have a variable $aet that I initialize in lua, but I wish I could use it in nginx too.

Here is my code:

location /getIp {
    default_type 'application/json';
    rds_json          on;

    content_by_lua '
        if ngx.var.host:match("(.*).nexus$") ~= nil then
            aet = ngx.var.host:match("(.-)%.")
            $aet = aet;
        end
    ';
    postgres_pass     database;
    postgres_query  "SELECT ip FROM establishment_view WHERE aet = $aet";
    postgres_output rds;
}

It does not work because in the query it does not know the variable aet :

nginx: [emerg] unknown "aet" variable

Upvotes: 5

Views: 18184

Answers (1)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

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

Read and write Nginx variable values.

value = ngx.var.some_nginx_variable_name
ngx.var.some_nginx_variable_name = value

Note that only already defined nginx variables can be written to. For example:

location /foo {
    set $my_var ''; # this line is required to create $my_var at config time
    content_by_lua_block {
        ngx.var.my_var = 123;
        ...
    }
}

That is, nginx variables cannot be created on-the-fly.

Upvotes: 17

Related Questions