freedoo
freedoo

Reputation: 711

Lua's package path in nginx

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.

Upvotes: 17

Views: 32205

Answers (2)

Kramer Li
Kramer Li

Reputation: 2486

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

Upvotes: 5

WolfTivy
WolfTivy

Reputation: 593

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.

Upvotes: 22

Related Questions