3

Following this post on using Lua to increase nginx’s flexibility and in reducing load on the web stack I am curious to know how people are using Lua to enhance nginx’s capability.

Are there any notable hacks, optimizations & observations using Lua? Hacks that people have used to discover capability with Nginx that would otherwise be complicated/impossible with a webserver or reverse proxy?

Edit:
Links:
http://thechangelog.com/post/3249294699/super-nginx-killer-build-of-nginx-build-for-luajit-plus
http://skillsmatter.com/podcast/home/scripting-nginx-with-lua/te-4729
http://devblog.mixlr.com/2012/06/26/how-we-use-nginx-lua-and-redis-to-beta-ify-mixlr/

Quintin Par
  • 4,293
  • 10
  • 46
  • 72

2 Answers2

2

Earlier we've written a solution that dynamically gets the document root based on the domain or domain alias specified. It uses a mysql database to store domainname to alias mappings. The link to it is http://www.logicwreck.com/index.php/2012/09/11/dynamic-hosts-for-nginx-with-database-storage-of-domain-and-alias-info/
A pretty interesting hack as it can prevent you from having multiple configured virtual hosts, and have just one instead.

Logic Wreck
  • 1,428
  • 9
  • 8
1

My document root solution also uses Lua but uses a bash script instead of a database. In short, it reverses the domain's parts and uses them as a directory structure. Within this structure, directories prefixed with _ can be used to differentiate document roots from sub-domains.

e.g. domain.com -> com/domain/_public sub.domain.com -> com/domain/sub/_public

server_name _ ~^(?<www>www\.)?(?<domain>[a-zA-Z0-9-\.]+)$;

set_by_lua $docRoot "
  local f = assert(io.popen('/path/to/conversion/script.sh '..ngx.var.domain, 'r'))
  local s = assert(f:read('*a'))
  f:close()
  return s
";

root /var/www/$docRoot/_public;

My conversion script is then:

echo $1 | tr "." "\n"  | tac | tr "\n" "/" | rev | cut -b 2- | rev | tr -d "\n"

The cut removes an additional slash while the final tr is needed because having a newline in the nginx root truncates the /_public

I run dozens of domains like this without any problems. It may be slower than a template based config generator for each domain but I prefer having a single file to troubleshoot.

  • 1
    and what if an alias is called rather then a domain name? in my case it's not an issue due to the db mapping. Better say if you have domainB as an alias of domainA. – Logic Wreck Sep 12 '12 at 11:39
  • I use "modifier" files for a variety of things including aliases. If foo.domain.com is an alias for sub.domain.com the file /var/www/com/domain/foo/_alias contains sub.domain.com and $domain + $docRoot are changed accordingly. – Arran Schlosberg Sep 12 '12 at 11:46