Purpose: use Lua to allow alias names for dynamic websites instead of symlinking to everywhere and forgetting about it
nginx.conf:
worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
events {
worker_connections 4096;
}
http {
include mime.types;
default_type application/octet-stream;
## Read in alias definitions in 2 arrays, array1 contains real existing accounts(websites), array2 the aliases for each account
## 2 arrays with different element sizes is easier to manage then having to split one array.
init_by_lua '
dsarr = {}; dsstr = {}; ds_as = 0;
local file = io.open("conf/aliases.txt", "r");
for ds_line2 in file:lines() do
ds_line = file:read();
table.insert (dsstr, ds_line);
table.insert (dsarr, ds_line2);
ds_as = ds_as + 1;
end
io.close (file);
';
server {
listen 80;
## This is a dynamic site, add a folder to storage and the website exists, it could not be any simpler :)
server_name .testdomcom.com;
if ($host ~ "^(w{3}\.)?(.*?)\.?testdomcom\.com$") { set $myuri $2; }
## However, when a client wants another website which must share the same data you could make a symbolic link or other fancy stuff
## I prefer to work with an alias, so we create an alias table (a simple -s reload and nginx reads the changes) and read it into memory with init_by_lua
## When a browser wants to access a website via it's alias we simply search the alias array and when found we map it to the real storage path
set_by_lua $notused '
y = 1; z = 0; s = ""; e = "";
for i = 1, ds_as, 1 do
s, e = string.find(dsstr[i], "?"..ngx.var.myuri); ## The ? is added to make sure we find unique names, see also the aliases.txt file
if s == nil then z=0; else z=1; break; end; ## if not nil, does not seem to work as expected
y = y + 1;
end
if z == 1 then ngx.var.myuri = dsarr[y] end;
';
set $myroot '/storagepool1/dynweb/$myuri';
## This will create a 404 when the site does not exist, uncomment the line below if you want to redirect to a default landing page
# if ($myuri = '') { set $myroot '/nginx/html'; }
root $myroot;
location / {
autoindex on;
index index.html index.htm;
}
}
}
Aliases.txt
test
?aliastest1?aliasxxx2
blabla
?aliasbla1?blaalias2
Add to host file for testing this setup;
127.0.0.1 www.testdomcom.com
127.0.0.1 test.testdomcom.com
127.0.0.1 aliastest1.testdomcom.com
127.0.0.1 aliasxxx2.testdomcom.com
127.0.0.1 blabla.testdomcom.com
127.0.0.1 aliasbla1.testdomcom.com
127.0.0.1 blaalias2.testdomcom.com
Questions;
1. Did I actually need Lua for this or could this be done in plain nginx?
2. Could the code block anywhere?
3. Can this be made better/faster?