今天因为客户的需要,他想实现一个服务器端的访问跳转服务。通过服务器端对访问进行限制。同样的url链接不同的ip进来就显示不同的页面。
现在通过宝塔直接安装Nginx openresty-1.19.9.1 和 redis
编写lua脚本 放到 /www/server/nginx/nginx/lua 目录下
hello.lua
ngx.say('hello ngx_lua!!!!');
test_redis.lua
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("set result: ", ok)
local res, err = red:get("dog")
if not res then
ngx.say("failed to get doy: ", err)
return
end
if res == ngx.null then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
mysql.lua
local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
ngx.say("failed to instantiate mysql: ", err)
return
end
db:set_timeout(1000)
local ok, err, errno, sqlstate = db:connect{
host = "127.0.0.1",
port = 3306,
database = "data",
user = "root",
password="pass",
max_packet_size = 1024 * 1024
}
if not ok then
ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
return
end
ngx.say("connected to mysql.")
local res, err, errno, sqlstate = db:query("drop table if exists cats")
if not res then
ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
res, err, errno, sqlstate = db:query("create table cats " .. "(id int not null primary key auto_increment, "
.. "name varchar(30))")
if not res then
ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
ngx.say("table cats created.")
res, err, errno, sqlstate = db:query("insert into cats(name) " .. "values (\'Bob\'),(\'\'),(null)")
if not res then
ngx.say("bad request: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
ngx.say(res.affected_rows, " rows inserted into table cats ", "(last insert id: ", res.insert_id, ")")
res, err, errno, sqlstate = db:query("select * from cats order by id asc", 10)
if not res then
ngx.say("bad result ", err, ": ", errno, ": ", sqlstate, ".")
return
end
local cjson = require "cjson"
ngx.say("result: ", cjson.encode(res))
local ok, err = db:set_keepalive(1000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
在网站的设置里面修改 配置文件 加入如下代码
location /lua {
set $test "hello, world.";
content_by_lua '
ngx.header.content_type = "text/plain";
ngx.say(ngx.var.test);
';
}
location /lua2 {
#lua_code_cache off;
default_type 'text/html';
content_by_lua_file lua/test_redis.lua;
}
location /lua3 {
#lua_code_cache off;
default_type 'text/html';
content_by_lua_file lua/mysql.lua;
}
重启 nginx
/www/server/nginx/nginx/sbin/nginx -t
/www/server/nginx/nginx/sbin/nginx -s reload
打卡浏览器 访问 http://127.0.0.1/lua2 可见返回
注意redis和数据库连接配置要改 下一节说跳转url