How do you test if an nginx variable is set in Lua?

3,151 views
Skip to first unread message

ssim...@elance.com

unread,
Mar 7, 2014, 5:18:49 PM3/7/14
to openre...@googlegroups.com
I'm trying to check if an nginx variable is set in lua. I'm doing

if ngx.var.myvar ~= "" then
   ...
end

where "myvar" isn't set in the nginx.conf. I'm getting

2014/03/07 14:09:50 [warn] 2127#0: *8 using uninitialized "myvar" variable, client: 127.0.0.1, server: localhost, request: "GET /no_cookies/index.html HTTP/1.1", host: "localhost:8080

in error.log. How do I test if the nginx variable is set?


Yichun Zhang (agentzh)

unread,
Mar 7, 2014, 5:31:33 PM3/7/14
to openresty-en
Hello!

On Fri, Mar 7, 2014 at 2:18 PM, simpson wrote:
> I'm trying to check if an nginx variable is set in lua. I'm doing
>
> if ngx.var.myvar ~= "" then

You should take into account nil values here too, that is, use the
following line instead:

if ngx.var.myvar and ngx.var.myvar ~= "" then

> where "myvar" isn't set in the nginx.conf. I'm getting
>
> 2014/03/07 14:09:50 [warn] 2127#0: *8 using uninitialized "myvar" variable,

This warning is generated by the standard ngx_rewrite module, not ngx_lua.

And this harmless warning can be disabled by adding the following line
to your nginx.conf:

uninitialized_variable_warn off;

See also http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#uninitialized_variable_warn

Best regards,
-agentzh

ssim...@elance.com

unread,
Mar 7, 2014, 5:58:38 PM3/7/14
to openre...@googlegroups.com
It seems my problem is related to variable scope. In nginx.conf I have

    location /no_cookies {
        access_by_lua_file "check_access.lua";
        proxy_pass http://$proxy_machine$uri;
       }
    location /sess_cookies {
        set $sess_block_over_time_prefix "sess_";
         access_by_lua_file "check_access.lua";
        proxy_pass http://$proxy_machine$uri;
       }

When I access a page in /no_cookies, I'm checking ngx.var.sess_block_over_time_prefix and getting the error in the error log. If I change the first nginx block to

      location /no_cookies {
        set $sess_block_over_time_prefix "";
        access_by_lua_file "check_access.lua";
        proxy_pass http://$proxy_machine$uri;
       }

then it works. I appears that if you use a variable in one block it must exist in the other blocks if you wish to test these variables in lua. Otherwise you get an error message. I don't know why this is the case.

ssim...@elance.com

unread,
Mar 7, 2014, 5:59:37 PM3/7/14
to openre...@googlegroups.com
OK. Sorry. Just saw your reply. I'll try that.

Reply all
Reply to author
Forward
0 new messages