Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


share|improve this question

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
A pretty interesting hack as it can prevent you from having multiple configured virtual hosts, and have just one instead.

share|improve this answer

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. -> com/domain/_public -> 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/ '..ngx.var.domain, 'r'))
  local s = assert(f:read('*a'))
  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.

share|improve this answer
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 is an alias for the file /var/www/com/domain/foo/_alias contains and $domain + $docRoot are changed accordingly. – Arran Schlosberg Sep 12 '12 at 11:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.