17

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.

xiaochen
  • 1,283
  • 2
  • 13
  • 30
freedoo
  • 691
  • 1
  • 5
  • 12
  • Are you using HttpLuaModule ? If so, Maybe you need to set lua_package_path and/or lua_package_cpath [see doc](http://wiki.nginx.org/HttpLuaModule#lua_package_path) – Mali Aug 05 '13 at 07:48
  • yeah, i have seen the api, but the path and cpath is relate with the '/', i doubt whether there are other methods which can make the path relate whith the nginx directory – freedoo Aug 05 '13 at 13:21

2 Answers2

22

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.

WolfTivy
  • 583
  • 3
  • 10
  • 8
    Of note, the `;;` appends the default package.path, and is not a typo. – Randall Jan 03 '18 at 18:13
  • this is the best use. Read this article also https://medium.com/@fabricebaumann/how-we-reduced-the-cpu-usage-of-our-lua-code-cc30d001a328 – uwevil Nov 20 '20 at 09:13
4

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
Kramer Li
  • 2,284
  • 5
  • 27
  • 55