lua脚本
获取请求中的参数
--lua的注释
--key-value形式取得所有的url上的参数--get型参数
local arg = ngx.req.get_uri_args()
for k,v in pairs(arg) do
ngx.say("[GET ] ", k, " :", v)
end
--key-value形式取得所有post的参数
ngx.req.read_body()-- 解析 body 参数之前一定要先读取 body
local arg = ngx.req.get_post_args()
for k,v in pairs(arg) do
ngx.say("[POST] ", k, " :", v)
end
读请求头信息
--读请求头信息
local headers = ngx.req.get_headers()
ngx.say("Host : ", headers.Host)
ngx.say("Host : ", headers["Host"])
ngx.say("--------------")
for k,v in pairs(headers) do
if type(v) == "table" then
--table.concat是table操作,意指将v内所有值合并
ngx.say(k, " : ", table.concat(v, ","))
else
ngx.say(k, " : ", v)
end
end
给lua脚本传递参数
location /setfile {
##给lua脚本传递参数
set_by_lua_file $val "/etc/nginx/lua/set.lua" $arg_a $arg_b;
echo $val;
}
local a=tonumber(ngx.arg[1])
local b=tonumber(ngx.arg[2])
return a + b
权限控制
location /access {
##权限控制
access_by_lua_file "/etc/nginx/lua/access.lua";
echo "welcome $arg_name !";
}
if ngx.var.arg_passwd == "123456"
then
return
else
ngx.exit(ngx.HTTP_FORBIDDEN)
end
重定向
location /rew {
##重定向
rewrite_by_lua 'ngx.exec("/hello")';
echo "I am rew";
}
location /redirect {
##页面重定向,是要生成内容的,因此使用content阶段
content_by_lua_block {
ngx.redirect("http://www.baidu.com", 302)
}
}
内容过滤
location /filter {
echo 'hello Peter';
echo 'you are welcome!';
##内容过滤
body_filter_by_lua_file "/etc/nginx/lua/filter.lua";
}
--ngx.arg[1]是输出块内容
local chunk = ngx.arg[1]
if string.match(chunk, "hello") then
ngx.arg[2] = true -- 设置为true,表示输出结束 eof
return
end
-- just throw away any remaining chunk data
ngx.arg[1] = nil
读redis值
location /redis {
##读redis值
content_by_lua_file "/etc/nginx/lua/redis.lua";
}
local redis = require "resty.redis"
--打开redis连接
local function open_redis()
local red = redis:new()
red:set_timeout(1000) -- 超时时间1 second
local res = red:connect('192.168.0.128',6379)
if not res then
return nil
end
res = red:auth(123456) --密码校验
if not res then
return nil
end
red.close = close
return red
end
--关闭连接
local function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.subscribed then
return nil, "subscribed state"
end
return sock:setkeepalive(10000, 50)
end
local key = 'name'
local val = "100"
local arg = ngx.req.get_uri_args() --取req里所有的参数
for k,v in pairs(arg) do
key = k
val = v
break;
end
local red = open_redis()
--local value = red:get(key) --取值
--red:set(key,val) --设新值
--close(red)
red:init_pipeline()
value = red:get(key)
red:set(key, val)
red:commit_pipeline()
--返回值到页面
ngx.say(key,':',value)
读mysql库
location /mysql {
##读mysql库
content_by_lua_file "/etc/nginx/lua/mysql.lua";
}
local mysql = require "resty.mysql"
local cjson = require "cjson"
--配置
local config = {
host = "192.168.0.128",
port = 3303,
database = "enjoy",
user = "root",
password = "root"
}
--打开连接
local function open_mysql()
local db, err = mysql:new()
if not db then
return nil
end
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect(config)
if not ok then
return nil
end
db.close = close
return db
end
--关闭连接
local function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.subscribed then
return nil, "subscribed state"
end
return sock:setkeepalive(10000, 50)
end
local db = open_mysql()
local sql = "select * from t_account "
--设置中文编码
ngx.header['Content-Type']="text/html;charset=UTF-8"
local res, err, errno, sqlstate = db:query(sql)
close(db)
if not res then
ngx.say(err)
return {}
end
--json方式输出
ngx.say(cjson.encode(res))
跨域
#是否允许请求带有验证信息
add_header Access-Control-Allow-Credentials true;
#允许跨域访问的域名,可以是一个域的列表,也可以是通配符*
add_header Access-Control-Allow-Origin http://static.enjoy.com;
#允许脚本访问的返回头
add_header Access-Control-Allow-Headers 'x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp';
#允许使用的请求方法,以逗号隔开
add_header Access-Control-Allow-Methods 'POST,GET,OPTIONS,PUT,DELETE';
#允许自定义的头部,以逗号隔开,大小写不敏感
add_header Access-Control-Expose-Headers 'WWW-Authenticate,Server-Authorization';
#P3P支持跨域cookie操作
add_header P3P 'policyref="/w3c/p3p.xml", CP="NOI DSP PSAa OUR BUS IND ONL UNI COM NAV INT LOC"';
if ($request_method = 'OPTIONS') {##OPTIONS类的请求,是跨域先验请求
return 204;##204代表ok
}
防盗
location ^~ /mall {
valid_referers *.enjoy.com;##对referer进行校验
if ($invalid_referer) {##校验不过,拒绝访问
return 404;
}
root /etc/nginx/html/gzip;
}
压缩
location ~ /(.*)\.(html|js|css|png)$ {
gzip on; # 启用gzip压缩,默认是off,不启用
# 对js、css、jpg、png、gif格式的文件启用gzip压缩功能
gzip_types application/javascript text/css image/jpeg image/png image/gif;
gzip_min_length 1024; # 所压缩文件的最小值,小于这个的不会压缩
gzip_buffers 4 1k; # 设置压缩响应的缓冲块的大小和个数,默认是内存一个页的大小
gzip_comp_level 1; # 压缩水平,默认1。取值范围1-9,取值越大压缩比率越大,但越耗cpu时间
root /etc/nginx/html/gzip;
}