nginx配置,配合lua编程实现
本次目的是使用nginx结合lua语言配置待检测功能的服务器
首先nginx配置项:
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; #资料附件的nginx转发路由 location ~* "^\/paperfiles\/\d{4,}\/\d{2}\/(\d{12})\_(\d{2,})\_(\d{1,})\_(1|2)(\.)(ashx|rar|pdf|doc|docx|txt|jar|zip|apk|jpg|caj|gif|PNG|ppt|pptx)?(.*)$" { #/paperfiles/2016/11/201611171915_01_2648817_1.docx?n=07.04工作安排1.docx&tocken=13a1c67cd9a05033911d0665beb79882×=1234565 charset utf-8; set $filetime $1; set $fileuserid $3;#userid set $lanmu $4;#userid set $oss_bucket "instrumentfile"; set $oss_auth_id "111"; set $oss_auth_key "222"; set $isfile "1"; rewrite_by_lua_file "lua/oss_auth_paper_bbs_files.lua"; } # internal redirect location @oss { proxy_pass http://instrumentfile.111.aliyuncs.com; } # internal redirect #bbs附件的nginx转发路由 location ~* "^\/bbsfiles\/files\/\d{4}\/\d{2}\/(\d{12})\_(\d{2,})\_(\d{1,})\_(3)(\.)(ashx|rar|pdf|doc|docx|txt|jar|zip|apk|jpg|caj|gif|PNG|ppt|pptx)?(.*)$" { #/bbsfiles/files/2005/02/200502021045_1165_1627481_3.doc?n=%e7%94%9f%e7%89%a9%e8%b4%a8%e7%87%83%e6%96%99%e9%87%87%e5%88%b6%e5%8c%96%e9%aa%8c%e6%b5%8b%e5%ae%9a%e6%96%b9%e6%b3%95.doc&tocken=13a1c67cd9a05033911d0665beb79882×=1234565 set $filetime $1; set $fileuserid $3;#userid set $lanmu $4;#userid set $oss_bucket "instrumentbbs"; set $oss_auth_id "111"; set $oss_auth_key "222"; set $isfile "1"; #1-文件,0-图片 rewrite_by_lua_file "lua/oss_auth_paper_bbs_files.lua"; } # internal redirect location @oss1 { proxy_pass http://instrumentbbs.111.aliyuncs.com; } #bbs的图片bbsfiles/images/2016/11/201611291717_01_2648817_3.jpg jpg,gif,jpeg,bmp,png location ~* "^\/bbsfiles\/images\/\d{4}\/\d{2}\/(\d{12})\_(\d{2,})\_(\d{1,})\_(3)(\.)(jpg|gif|jpeg|bmp|png)$" { set $filetime $1; set $fileuserid $3;#userid set $lanmu $4;#userid set $oss_bucket "instrumentbbs"; set $oss_auth_id "111"; set $oss_auth_key "222"; set $isfile "0";#1-文件,0-图片 rewrite_by_lua_file "lua/oss_auth_paper_bbs_files.lua"; } #网展配置 location ~*/17img/{ set $filetime "1111"; set $fileuserid "1111";#userid set $lanmu "111";#userid set $oss_bucket "instrumentnetshow"; set $oss_auth_id "111"; set $oss_auth_key "222"; set $isfile "2";#1-文件,0-图片,2-网展 rewrite_by_lua_file "lua/oss_auth_paper_bbs_files.lua"; #rewrite ^((.+?\.(jpg|gif|jpeg|bmp|png)?)\!(.*)) $2@!$4 last; #rewrite ^((.+?\.(jpg|gif|jpeg|bmp|png)?)\!(\w(\d+)\w(\d+))) $2?x-oss-process=image/resize,w_$5,h_$6 last; #proxy_pass http://instrumentnetshow.111.aliyuncs.com; } location @oss2 { rewrite ^((.+?\.(jpg|gif|jpeg|bmp|png)?)\!(\w(\d+)\w(\d+))) $2?x-oss-process=image/resize,w_$5,h_$6 last; proxy_pass http://instrumentnetshow.222.aliyuncs.com; } } }
加载的lua 配置文件源码:
-- has been sorted in alphabetical order local signed_subresources = { 'acl', 'append', 'bucketInfo', 'cname', 'commitTransition', 'comp', 'cors', 'delete', 'lifecycle', 'location', 'logging', 'mime', 'notification', 'objectInfo', 'objectMeta', 'partData', 'partInfo', 'partNumber', 'policy', 'position', 'referer', 'replication', 'replicationLocation', 'replicationProgress', 'requestPayment', 'response-cache-control', 'response-content-disposition', 'response-content-encoding', 'response-content-language', 'response-content-type', 'response-expires', 'restore', 'security-token', 'tagging', 'torrent', 'uploadId', 'uploads', 'versionId', 'versioning', 'versions', 'website' } function string.startswith(s, start) return string.sub(s, 1, string.len(start)) == start end local function get_canon_sub_resource() local args = ngx.req.get_uri_args() -- lower keys local keys = {} for k, v in pairs(args) do keys[k:lower()] = v end -- make resource string local s = '' local sep = '?' for i, k in ipairs(signed_subresources) do v = keys[k] if v then -- sub table v = type(v) == 'table' and v[1] or v s = s .. string.format("%s%s=%s", sep, k, v) sep = '&' end end return s end local function get_canon_resource() resource = '' object = ngx.unescape_uri(ngx.var.uri) sub = get_canon_sub_resource() return string.format("/%s%s%s", ngx.var.oss_bucket, object, sub) end local function get_canon_headers() -- default: <lowerkey, value> local headers = ngx.req.get_headers() local keys = {} for k, v in pairs(headers) do if string.startswith(k, 'x-oss-') then -- client must assemble the same header keys if type(v) ~= 'string' then return nil end table.insert(keys, k) end end -- sorted in alphabetical order table.sort(keys) for i, key in ipairs(keys) do keys[i] = key .. ':' .. headers[key] .. '\n' end return table.concat(keys) end local function calc_sign(key, method, md5, type_, date, oss_headers, resource) local sign_str = string.format('%s\n%s\n%s\n%s\n%s%s', method, md5, type_, date, oss_headers, resource) ngx.log(ngx.ERR, "SignStr:", sign_str, "\n") ngx.log(ngx.ERR, "key:", key, "\n") ngx.log(ngx.ERR, "sign_str:", sign_str, "\n") local sign_result = ngx.encode_base64(ngx.hmac_sha1(key, sign_str)) return sign_result, sign_str end local function oss_auth() local method = ngx.req.get_method() local content_md5 = ngx.var.http_content_md5 or '' local content_type = ngx.var.http_content_type or '' local date = ngx.var.http_x_oss_date or ngx.var.http_date or '' if date == '' then date = ngx.http_time(ngx.time()) ngx.req.set_header('Date', date) end local resource = get_canon_resource() local canon_headers = get_canon_headers() local sign_result, sign_str = calc_sign(ngx.var.oss_auth_key, method, content_md5,content_type, date, canon_headers, resource) local auth = string.format("OSS %s:%s", ngx.var.oss_auth_id, sign_result) local isfile = ngx.var.isfile; if isfile=="1" then --刘小草添加开始 --验证authon,防止乱下载开始-- --通过时间戳,保证失效时间开始 local times=tonumber(ngx.var['arg_times']); local cur_timestamp = os.time() local one_minute_timestamp = 60 local cur_valid_timestamp =times+one_minute_timestamp*5 local flag="2" local tochenkey="liuxiaocao" local tocken=ngx.var['arg_tocken'] local fileuserid=ngx.var['fileuserid'] local filetime=ngx.var['filetime'] local newTocken= ngx.md5(filetime..fileuserid..times..tochenkey); if (cur_timestamp>cur_valid_timestamp) then --已经过期 flag="0" end --通过时间戳,保证失效时间结束 --验证tochen有效性开始 if flag=="2" then if (tocken~=newTocken) then flag="1" end end --验证tochen有效性结束 --验证authon,防止乱下载结束-- if flag=="2" then local usragent=ngx.var.http_user_agent local filename1 =nil; filename1 = ngx.req.get_uri_args()["n"]; if (string.match(usragent, "Trident")=="Trident") then filename1 = ngx.escape_uri(filename1);--IE浏览器 --filename1 = "222"; --else -- filename1="333"; --filename1=ngx.escape_uri(filename1) end filename1=string.gsub(filename1," ","_");--将空格替换为下划线,防止firefox传递下载附件出错 attachment = "attachment;filename="..filename1 ngx.header["Content-Disposition"] = attachment --刘小草添加结束 ngx.req.set_header('Authorization', auth) lanmu=ngx.var['lanmu'] if (lanmu=="3") then--论坛 ngx.exec("@oss1") else ngx.exec("@oss") end elseif flag=="1" then ngx.say("".."filetime:"..filetime..";fileuserid:"..fileuserid..";times:"..times.."zuhe:"..(filetime..fileuserid..times..tochenkey).."newTocken:"..newTocken); else ngx.say("您的访问地址有误!"..flag..';cur_timestamp:'..cur_timestamp..";times:"..times); end elseif isfile=="2" then --ngx.say(".imagesshow.") local filename =nil; filename = ngx.var.uri; filename=string.gsub(filename,"//","/"); ngx.req.set_uri(filename,false); return ngx.exec("@oss2") else --ngx.say(".images.") ngx.req.set_header('Authorization', auth) ngx.exec("@oss1") end end -- main res = oss_auth() if res then ngx.exit(res) end
在nginx中使用lua语言,首先需要安装lua模块,然后在nginx中的location中使用:
rewrite_by_lua_file "lua/oss_auth_paper_bbs_files.lua";
在lua语言中:
获取nginx的url:ngx.var.uri;
获取nginx的url的参数:ngx.req.get_uri_args()["参数名称"];
替换字符串:string.gsub(filename,"//","/");
重写url:ngx.req.set_uri(url,false);
重定向:ngx.exec("@oss2")
说明@oss2是在nginx中设置的如下:是一个location
location @oss2 { rewrite ^((.+?\.(jpg|gif|jpeg|bmp|png)?)\!(\w(\d+)\w(\d+))) $2?x-oss-process=image/resize,w_$5,h_$6 last; proxy_pass http://instrumentnetshow.111.aliyuncs.com; }