uhttpd是OpenWrt上经常使用的、轻量级的响应http申请的web服务器,可以将申请分发给文件、CGI解释器(cgi_prefix,解释器一般为perl或者是php-cgi)或者Lua解释器(lua_prefix)。
由于使用Lua解释器开发时,由lua_handler指定的.lua文件每次修改都需要重新启动uhttpd才能生效,因此将.lua文件作为CGI脚本来调试会方便很多。
这里先以标准的Lua解释器配置为例,看uhttpd如何配置标准的lua_prefix:
编辑文件:“/etc/config/uhttpd”,将其中的:
#option lua_prefix /luci
#option lua_handler
/usr/lib/lua/luci/sgi/uhttpd.lua
去掉符号“#”(即去掉注释),并修改为:
option lua_prefix /lua
option lua_handler /root/http.lua
保存退出(如果使用“vi”编辑,按ESC键,再输入“:x”,回车键即可保存退出)。
请确认存在“/root/http.lua”文件,并且其内容中包含一个名为handle_request函数,内容如下:
#!/usr/bin/lua
function handle_request(env)
uhttpd.send("hello, world")
end
使用命令“/etc/init.d/uhttpd
restart”重新启动uhttpd服务,然后使用浏览器访问“http://{openwrt_ip}/lua/http.lua”,即可以看到.lua文件的响应内容。
下面进入正题,需要配置将Lua当作CGI脚本解释器使用。
编辑文件:“/etc/config/uhttpd”,将其中的:
option lua_prefix /lua
option lua_handle /root/uhttpd.lua
在这两行前添加符号“#”(即注释掉这两行)。
并同时将其中的:
option cgi_prefix /cgi-bin
去掉注释,再添加下面这行:
list interpreter ".lua=/usr/bin/lua"
保存退出。
请确认存在“/www/cgi-bin”目录,同时该目录下存在文件“date.lua”,该文件内容如下:
#!/usr/bin/lua
io.write("Content-type:
text/html\n\n")
io.write(os.date("%x", os.time()))
重新启动uhttpd服务,然后使用浏览器访问“http://{openwrt_ip}/cgi-bin/date.lua”,即可以看到“date.lua”输出的当前系统的日期。
特别注意:CGI脚本必须要输出“Content-type:
text/html\n\n”,uhttpd才会认为脚本正确进行了响应,才会输出内容到浏览器。