背景
- 使用openresty搭建website服务器,用户访问图片可以记录用户的访问记录
服务搭建
部署步骤
- 前提: 服务搭建
- 修改 my_server_block.conf文件;
- 配置 匹配/lua_share/路径,响应 share_pic_visit.lua 文件逻辑.
- 禁止 其他方式访问lua文件,避免源码文件被下载.
server {
listen 0.0.0.0:8080;
root /app;
index index.htm index.html;
location /lua_share/ {
lua_code_cache off;
content_by_lua_file /app/lua/share_pic_visit.lua;
}
location ~* .lua$ {
deny all;
}
}
目录结构示例

share_pic_visit.lua
local request_uri = ngx.var.request_uri
request_uri = string.gsub(request_uri, "/lua_share/", "/")
local res = ngx.location.capture(request_uri)
if res.status == 200 then
ngx.print(res.body)
else
ngx.log(ngx.ERR, "Failed to capture URI: ", request_uri)
end
local args = ngx.req.get_uri_args()
local areaid, numid, timestamp = args.areaid, args.numid, args.timestamp
if not areaid or not numid or not timestamp then
ngx.log(ngx.ERR, "Invalid areaid or numid or timestamp")
return
end
local function connect_to_redis(ip, port, password)
local redis = require("resty.redis")
local rds = redis:new()
rds:set_timeout(1000)
local ok, err = rds:connect(ip, port)
if not ok then
ngx.log(ngx.ERR, "connect to redis error: ", err)
return nil, err
end
local resp, err2 = rds:auth(password)
if not resp then
ngx.log(ngx.ERR, "failed to authenticate: ", err2)
return nil, err2
end
return rds, nil
end
local function close_redis(rds)
if not rds then
return
end
local ok, err = rds:close()
if not ok then
ngx.log(ngx.ERR, "close redis error: ", err)
end
end
local environment = "develop"
local RedisConfig = {
production = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" },
test = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" },
develop = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" }
}
local rdsConfig = RedisConfig[environment]
local rds, err = connect_to_redis(rdsConfig.ip, rdsConfig.port, rdsConfig.password)
if not rds then
ngx.log(ngx.ERR, "connect to redis error: ", err)
return close_redis(rds)
end
local RedisKey_UserShareVisitPic = "user_share_visit_pic_%d_%d_%s"
local rdsKey = string.format(RedisKey_UserShareVisitPic, areaid, numid, timestamp)
local ok, err = rds:set(rdsKey, os.time() * 1000)
if not ok then
ngx.log(ngx.ERR, "failed to incr: ", err)
return close_redis(rds)
end
ok, err = rds:ttl(rdsKey)
if ok == -1 then
rds:expire(rdsKey, 60 * 10)
end
close_redis(rds)