Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx Lua Scripting

Tags:

nginx

lua

One of the really cool things about Nginx is that you can take control of what it does by injecting Lua script at various phases of request processing. I have successfully used the rewrite_by_lua/file directive to examine the body of the incoming request and inject extra request headers for downstream processing by PHP. e.g.

location /api{
  rewrite_by_lua_file "/path/to/rewrite.lua";
  lua_need_request_body "on";

}

and then in rewrite.lua

local uri = ngx.var.request_uri;
//examine the URI and inject additional headers
ngx.req.set_header('headerName','headerValue');

What I can also do at this stage is inject response headers. For example

local cookieData = "cookieName=value;path=/;";    
ngx.header['Set-Cookie'] = cookieData;

No issues thus far but this is not quite what I want to do. The workflow I have in mind goes like this

  • Examine the URI & inject extra request headers.
  • My PHP scripts examine the extra request headers, process the incoming data as required and may inject extra response headers
  • I then want to examine the response headers in another Nginx Lua script and inject cookies at that stage.

Injecting extra response headers via my PHP script is no problem at all. I thought that in order to examine those extra headers I would just need to setup

location /api {
  header_filter_by_lua_file "path/to/header.lua";
}

with header.lua doing things like

local cookieData = "cookieName=value;path=/;";    
ngx.header['Set-Cookie'] = cookieData;

The principle sounds perfect. However, I find that my header_filter_by_lua_file directives just get ignored - no errors reported in the Nginx log when I reload the configuration.

I must be doing something wrong here but I cannot see what it might be. I am using nginx 1.6.2 on Ubuntu 14.10 (x64). Nginx having been installed with apt-get install nginx-extras.

I'd be most grateful to anyone who might be able to explain how to get header_filter_by_* functioning correctly.

like image 253
DroidOS Avatar asked Dec 06 '25 18:12

DroidOS


1 Answers

It's not a feature of vanilla nginx. You need to install openresty (instead of nginx).

See http://openresty.org/#Download and then http://openresty.org/#Installation

like image 69
daurnimator Avatar answered Dec 08 '25 07:12

daurnimator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!