Nginx Lua 获取真实 IP 地址 - 解决 'attempt to call global 'get_real_ip' (a nil value)' 错误
Nginx Lua 获取真实 IP 地址 - 解决 'attempt to call global 'get_real_ip' (a nil value)' 错误
这个错误提示表明你尝试调用了一个名为 'get_real_ip' 的全局变量,但它的值为 nil,也就是不存在。这通常发生在你没有正确加载定义了 get_real_ip 函数的 Lua 文件的情况下。
解决方案
要使用 get_real_ip 函数,你需要确保在当前的 Lua 脚本中正确加载了包含它的 Lua 文件。可以使用类似于 require('file') 的语句来加载文件。例如,如果你的 get_real_ip 函数定义在名为 utils.lua 的文件中,你可以在当前脚本中使用以下语句来加载它:
local utils = require('utils')
local ip = utils.get_real_ip()
这样,你就可以成功调用 get_real_ip 函数了。
代码示例
以下是一个包含 get_real_ip 函数的 utils.lua 文件示例:
function get_real_ip()
local headers = ngx.req.get_headers()
local remote_addr = ngx.var.remote_addr
if headers['X-Real-IP'] then
remote_addr = headers['X-Real-IP']
elseif headers['X-Forwarded-For'] then
remote_addr = headers['X-Forwarded-For']
end
return remote_addr
end
在你的 Nginx 配置文件中,你需要将 utils.lua 文件加载到你的 Lua 脚本中,例如:
location / {
content_by_lua '
local utils = require('utils')
local ip = utils.get_real_ip()
ngx.say(ip)
';
}
总结
'attempt to call global 'get_real_ip' (a nil value)' 错误通常是由于没有正确加载包含 get_real_ip 函数的 Lua 文件导致的。通过使用 require() 函数加载文件并正确调用函数,就可以解决这个问题。
原文地址: https://www.cveoy.top/t/topic/njZo 著作权归作者所有。请勿转载和采集!