Nginx: embedding Lua into webserver

Lua is a tiny but powerful programming language. Due to its small memory footprint (about hundreds of kilobytes) it’s widely used in application which need to be extended with more complex logic. For instance, Salvatore Sanfilippo has published a  post describing how you can use power of Lua with Redis. It also applied to nginx, you can use Lua in its configuration files to get them more flexible. Sometimes it can be handy. Here is what you need to do to get nginx with Lua in core. We will use Lua module for nginx. At the end we will have nginx rpm package with Lua support. I assume that you already have rpmbuild environment and use Fedora 15. You also need to have Lua installed. Firstly download and unpack ngx_lua and to your SOURCES. You will also need ngx_devel_kit, it should be unpacked to SOURCES as well. After that you need to download srpm of nginx and install it.

yumdownloader --source nginx
rpm -ivh nginx-1.0.5-1.fc15.src.rpm

Besides you need to download nginx tarboll with 1.0.6 version and put it  to SOURCES. Change Version line to “1.0.6” and add next line to the configure section:


Now we are ready to build rpm.

rpmbuild -bb ~/rpmbuild/SPECS/nginx.spec

If there are  no errors you should get nginx rpm package with Lua support:

[root@playground ~]# ls ~/rpmbuild/RPMS/x86_64/nginx-1.0.6-1.fc15.x86_64.rpm
[root@playground ~]#

Let’s install it and test.

rpm -ivh ~/rpmbuild/RPMS/x86_64/nginx-1.0.6-1.fc15.x86_64.rpm

As you can see nginx was built with Lua:

[root@playground ~]# ldd /usr/sbin/nginx | grep lua => /usr/lib64/ (0x0000003331600000)
[root@playground ~]#

Add next section to nginx configuration file (thats is a slightly modified example from the documentation):

location /foo {
set $diff ''; # we have to predefine the $diff variable here
set_by_lua $sum '
local a = 32
local b = 56
ngx.var.diff = a - b; -- write to $diff directly
return a + b; -- return the $sum value normally
ngx.print(ngx.var.sum); ngx.say(ngx.var.diff);';

Start nginx and make a request:

[root@playground ~]# /etc/init.d/nginx start ; curl localhost/foo
Restarting nginx (via systemctl): [ OK ]
[root@playground ~]#

Lua is working! More information on ngx_lua module can be found on github page or nginx wiki.  To get more information about Lua you can refer to Lua 5.1 Reference Manual.
Upd. Luckily for Ubuntu users, you can just install nginx-extras package to get nginx with Lua. Actually this package also contains modules nginx-echo,  nginx-push-0.692 and nginx-upstream-fair.


Didn’t find the answer to your question? Ask it our administrators to reply we will publish on website.

Leave a Reply

Your email address will not be published. Required fields are marked *