nginx 第三方模块:ngx_devel_kit、HttpLuaModule
nginx.conf 配置:
lua_shared_dict clients 1m; lua_code_cache on; init_by_lua 'clients, cjson = ngx.shared.clients, require "cjson"';
server { listen 8181; server_name localhost; resolver 8.8.8.8; location / { access_by_lua_file /srv/lua-script/auth_basic.lua; proxy_set_header HOST $http_host; proxy_pass http://$http_host$request_uri; } location = /Authorization { auth_basic "Secure Area"; auth_basic_user_file htpasswd.conf; content_by_lua ' local url = ngx.req.get_uri_args()["url"] local hasUrl = ngx.re.match(url, ".+") url = (hasUrl and url) or "http://"..ngx.var.http_host ngx.redirect(url) '; } location = /http-proxy-list { default_type 'text/html'; content_by_lua_file /srv/lua-script/http_proxy_list.lua; } }
auth_basic.lua:
local val, auth = clients:get(ngx.var.remote_addr), ngx.req.get_headers()["Authorization"] if auth ~= nil then val = auth clients:set(ngx.var.remote_addr, val) end if val == nil then local url = ngx.escape_uri("http://"..ngx.var.http_host..ngx.var.uri) return ngx.redirect("http://"..ngx.var.http_host.."/Authorization?url="..url) end
http_proxy_list.lua:
if ngx.var.host == "proxy" then if ngx.req.get_uri_args()["clear"] ~= nil then clients:flush_all() return ngx.redirect("http://"..ngx.var.http_host..ngx.var.uri) else ngx.say(cjson.encode(clients:get_keys())) end else ngx.exit(404) end