Hello!
On Thu, Mar 6, 2014 at 2:41 AM, greekduke wrote:
> I want to change my nginx configuration below that uses the eval module with
> lua. I just want to get the result of the query into the result variable in
> order to use it for some checks. Any ideas how to do it?
>
It should look like this (untested):
location = /entry {
set $result '';
rewrite_by_lua '
local res = ngx.location.capture("/pg")
if res.status < 300 then
ngx.var.result = res.body
end
';
# here we just use the "echo" directive as the content
# handler for this location
echo $result;
}
location = /pg {
internal;
postgres_pass db;
postgres_query "select cast(count(url) as varchar),'0' from urls
where url like '%$http_host%' union
select calledstationid,callingstationid from mappings
where framedipaddress='$http_x_forwarded_for'";
postgres_output text;
}
BTW, your SQL query is vulnerable to SQL injection attacks. You should
either validate the values of the "Host" and "X-Forwarded-For" headers
or just quote their values before interpolating them into your SQL
string (or both). It is trivial to do in your rewrite_by_lua directive
with a little bit of Lua anyway ;)
The "echo" directive is just used as an example above. Replace it with
your normal content handlers.
Be aware that all the ngx_rewrite module's directives run before
rewrite_by_lua by default, so if you want to do funny things with the
$result variable in rewrite phase (like value post-processing and even
redirects), you'd better do all these in rewrite_by_lua with Lua code.
It's recommended to read the ngx_lua official manual to save your time:
https://github.com/chaoslawful/lua-nginx-module#readme
Best regards,
-agentzh