具有单独 lua_package_path 变量的 NGINX 虚拟主机

NGINX virtual hosts with seperate lua_package_path variables

我正在尝试将两个 (Openresty) Lua Web 应用程序作为 NGINX 的虚拟主机提供服务,它们都需要自己独特的 lua_package_path,但很难正确配置。

# Failing example.conf

http {
  lua_package_path = "/path/to/app/?.lua;;"

  server{
    listen       80;
    server_name  example.org
  }
}

http {    
  lua_package_path = "/path/to/dev_app/?.lua;;"

  server{
    listen       80;
    server_name  dev.example.org
  }
}
  1. 如果您定义 http 两次(每个主机一个),您将收到此错误:[emerg] "http" directive is duplicate in example.conf

  2. 如果在 server 块中定义 lua_package_path,您将收到此错误:[emerg] "lua_package_path" directive is not allowed here in example.conf

  3. 如果您在 http 块中定义了两次 lua_package_path(无论如何都没有任何意义),您将收到此错误:[emerg] "lua_package_path" directive is duplicate in example.conf

使用自己的 lua_package_path 服务多个 (Openresty) Lua 应用程序的最佳实践是什么,它们是同一 IP 和端口上的虚拟主机?

我几个月前遇到过这个问题。 我不建议在同一台服务器上不使用调试和发布项目。例如,您为两个(调试和发布)密钥启动一个 nginx 应用程序可能会导致意外行为。 但是,尽管如此,您可以设置:

  1. package.path = './mylib/?.lua;' .. package.path 在 lua-脚本中。
  2. 您可以设置自己的 local DEBUG = false 状态并在应用内进行管理。
  3. 很明显,使用其他机器进行调试。 Imo,最好的解决方案。
  4. 执行不同的my.release.luamy.debug.lua文件:
http {
          lua_package_path "./lua/?.lua;/etc/nginx/lua/?.lua;;";



        server{
            listen       80;
            server_name  dev.example.org;
              lua_code_cache off;


        location / {
                default_type text/html;
                content_by_lua_file './lua/my.debug.lua';
              }
        }
        server{
            listen       80;
            server_name  example.org

        location / {
                default_type text/html;
                content_by_lua_file './lua/my.release.lua';
              }
          }
        }

修复了它从 NGINX 配置中删除 lua_package_path(因为 OpenResty 包已经负责加载包)并将我的 content_by_lua_file 指向我的应用程序的绝对完整路径:/var/www/app/app.lua

# example.conf

http {

  server{
    listen       80;
    server_name  example.org

    location / {
      content_by_lua_file '/var/www/app/app.lua';
    }
  }

  server{
    listen       80;
    server_name  dev.example.org

    location / {
      content_by_lua_file '/var/www/app_dev/app.lua';
    }

  }
}

之后,我将其包含在我的 app.lua 文件的顶部:

-- app.lua

-- Get the current path of app.lua
local function script_path()
   local str = debug.getinfo(2, "S").source:sub(2)
   return str:match("(.*/)")
end

-- Add the current path to the package path
package.path = script_path() .. '?.lua;' .. package.path

-- Load the config.lua package
local config = require("config")

-- Use the config
config.env()['redis']['host']

...

这让我可以从与 app.lua

相同的目录中读取 config.lua
-- config.lua

module('config', package.seeall)

function env()
  return {
    env="development",
    redis={
      host="127.0.0.1",
      port="6379"
    }
  }
end

使用它,我现在可以使用多个具有自己的包路径的虚拟主机。

@Vyacheslav 谢谢指点package.path = './mylib/?.lua;' .. package.path!这真的很有帮助!不幸的是,它还一直使用 NGINX conf root 而不是我的应用程序 root。即使在路径前面加上 .