I am now programming in Lua with nginx. I write my Lua file and place it in a directory in /usr/local/nginx/lua
. Then in nginx.conf
I write a location, such as
location /lua {
lua_need_request_body on;
content_by_lua_file lua/test.lua;
}
When I access this location through Nginx, the Lua script will be executed.
In a Lua file, one usually can include your own Lua module, and indicate the search path
common_path = '../include/?.lua;'
package.path = common_path .. package.path
In common Lua programming, a relative path is relative to my Lua file.
But with nginx, the relative paths are relative to the directory where I start Nginx.
Like, I am in /usr/local/nginx
and execute sbin/nginx
, then in Lua package.path
will be the /usr/local/include
.
If I am in /usr/local/nginx/sbin
and execute ./nginx
, then in Lua package.path
will be /usr/local/nginx/include
.
I think the directory I start the nginx server should not been limited, but I don't know how to resolve this.
Nginx+Lua is a self-contained web server embedding the scripting language Lua. Powerful applications can be written directly inside Nginx without using cgi, fastcgi, or uwsgi. By adding a little Lua code to an existing Nginx configuration file, it is easy to add small features.
OpenResty is a web platform based on nginx which can run Lua scripts using its LuaJIT engine. The software was created by Yichun Zhang. It was originally sponsored by Taobao before 2011 and was mainly supported by Cloudflare from 2012 to 2016.
Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.
You want to modify the Lua package.path
to search in the directory where you have your source code. For you, that's lua/
.
You do this with the lua_package_path
directive, in the http block (the docs say you can put it in the top level, but when I tried that it didn't work).
So for you:
http {
#the scripts in lua/ need to refer to each other
#but the server runs in lua/..
lua_package_path "./lua/?.lua;;";
...
}
Now your lua scripts can find each other even though the server runs one directory up.
You can use $prefix now.
For example
http{
lua_package_path "$prefix/lua/?.lua;;";
}
And start your nginx like this
nginx -p /opt -c /etc/nginx.conf
Then the search path will be
/opt/lua
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With