正则匹配链接和获取参数,利用lua根据参数指向不同location 代码块如下:
server {
listen 80;
server_name loc.lua.com;
index index.php index.html;
root /var/www/course-front-api/public;
location ~ ^(.*)/\.svn/ {
return 404;break;
}
location = /request_body {
client_max_body_size 50k;
client_body_buffer_size 50k;
content_by_lua_block {
ngx.req.read_body() -- explicitly read the req body
local data = ngx.req.get_body_data()
if data then
ngx.say("body data:")
ngx.print(data)
return
end
-- body may get buffered in a temp file:
local file = ngx.req.get_body_file()
if file then
ngx.say("body is in file ", file)
else
ngx.say("no body found")
end
}
}
# rewrite ^/a_([0-9]+)\.html$ /index.php/?aid=$1 last;
--匹配地址
location ~ ^/a_([0-9]+)\.html$ {
default_type 'text/plain';
content_by_lua_block {
local m, err = ngx.re.match(ngx.var.uri, "[0-9]+")
if err then
ngx.log(ngx.ERR, "error: ", err)
return
end
-- ngx.say('Hello,world!',ngx.var.uri,m[0])
-- 可以根据自己的需求,查库或者redis
local file = io.open("/var/www/aiops/docker/base_image/nginx/sites/id.txt",'r')
if not file then
ngx.say("can not open file")
end
local content = file:read('*all')
file:close()
-- ngx.say(content)
-- json格式转化
local json = require("cjson")
local ids = json.decode(content)
local tc = 0
for i, v in pairs(ids.id) do
if m[0] == v then
tc = 1
end
end
--指向不同location
if tc == 1 then
ngx.exec("@bar")
else
ngx.exec("@two")
end
}
}
location @bar {
# MIME type determined by default_type:
default_type 'text/plain';
content_by_lua_block {
ngx.say('Hello,world!')
}
}
location @two {
# MIME type determined by default_type:
default_type 'text/plain';
content_by_lua_block {
ngx.say('Hello,world two!')
}
}
location /nginx_status {
stub_status on;
access_log off;
}
location ~ /.ht {
deny all;
}
#access_log off;
error_log /var/log/nginx/loc.lua_error.log;
access_log /var/log/nginx/loc.lua_access.log;
}