1、动态输出
打开E:StudyOpenresty-1.19.9.1-win64目录中的conf/nginx.conf文件[en]Open the conf/nginx.conf file in the E: study openresty openresty-1.19.9.1-win64 directory
在server中增加一下代码
javascript;gutter:true;
location /hello {
default_type text/html;
content_by_lua 'ngx.say("hello, world")';
}</p>
<pre><code>
运行后的效果如下:本地主机/Hello[en]<u>After running, the effect is as follows: localhost/hello</u>

2、优化动态输出
上述代码直接将Lua代码写在nginx配置中,维护起来不方便。让我们将其从一个单独的文件中取出,并将其放入E:StudyOpenrestyOpenresty-1.19.9.1-win64/lua目录中。[en]<u>The above code directly writes the lua code in the nginx configuration, which is not convenient to maintain. Let's take it out of a separate file and put it in the E: study openresty openresty-1.19.9.1-win64/lua directory.</u>
创建新的lua/hello2.lua[en]<u>Create a new lua/hello2.lua</u>
;gutter:true;
ngx.say("hi,world")
配置如下[en]The configuration is as follows
javascript;gutter:true;
location / {
default_type text/html;
content_by_lua_file lua/hello2.lua;
}</p>
<pre><code>
重新启动nginx nginx-s重新加载[en]<u>Restart nginx nginx-s reload</u>

身份验证:本地主机[en]<u>Authentication: localhost</u>

上述Lua文件是固定的,如何动态指定Lua文件名。[en]<u>The above lua file is fixed, how to dynamically specify the lua file name.</u>
1) 增加配置
;gutter:true;
location ~ /lua/(.+) {
default_type text/html;
content_by_lua_file lua/$1.lua;
}
2、增加lua/one.lua
javascript;gutter:true;
ngx.print("hi,one")</p>
<pre><code>
添加Lua/Tow.lua[en]<u>Add lua/tow.lua</u>
;gutter:true;
ngx.print("hi,two")
3、验证
localhost/lua/one

localhost/lua/two

3、接收参数
1 ) lua/req.lua 文件
支持GET和POST参数[en]GET and POST parameters are supported
javascript;gutter:true;
local _M = {}
-- 获取http get/post 请求参数
function _M.getArgs()
-- 获取http请求方式 GET or POST
local request_method = ngx.var.request_method
-- 这里是一个table,包含所有get请求参数
local args = ngx.req.get_uri_args()
-- 如果是post参数获取
if "POST" == request_method then
-- 先读取请求体
ngx.req.read_body()
-- 这里也是一个table,包含所有post请求参数
local postArgs = ngx.req.get_post_args()
if postArgs then
for k, v in pairs(postArgs) do
args[k] = v
end
end
end
return args
end</p>
<p>return _M</p>
<pre><code>
2)conf/nginx.conf 添加
;gutter:true;
http {
# 这里一定要指定package_path,否则会找不到引入的模块,然后会500
lua_package_path E:\study\openresty\openresty-1.19.9.1-win64\lua\?.lua;
server {
listen 80;
server_name localhost;
location ~ /lua/(.+) {
default_type text/html;
content_by_lua_file lua/$1.lua;
}
}
3) 创建lua/test.lua 文件
javascript;gutter:true;
-- 引入req模块
local req = require "req"</p>
<p>-- 获取请求参数列表
local args = req.getArgs();
-- 获取key为name的值
local name = args['name']</p>
<p>-- 如果不存在指定默认值
if name == nil or name == "" then
name = "default name zhang san"
end</p>
<p>-- 输出结果
ngx.say("hello " .. name .. "!")
4)验证
http://localhost/lua/test?name=nick
Original: https://www.cnblogs.com/linlf03/p/15936873.html
Author: work hard work smart
Title: Openresty快速入门
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/5941/
转载文章受原作者版权保护。转载请注明原作者出处!