-- 获取客户端 IP 地址 local remote_addr = ngx.var.remote_addr -- 判断 IP 不等于 8.8.8.8 进行认证 if remote_addr ~= "8.8.8.8" then -- 获取 HTTP 头中的 Authorization 字段 local auth_header = ngx.var.http_Authorization if auth_header then -- 获取 Basic 认证信息 local decoded = ngx.decode_base64(string.sub(auth_header, 7)) if decoded then -- 拆分用户名和密码 local split_index = string.find(decoded, ":") local username = string.sub(decoded, 1, split_index - 1) local password = string.sub(decoded, split_index + 1) -- 检查用户名和密码是否正确 if username == "admin" and password == "admin" then -- 验证通过,继续处理请求 return end end end -- 认证失败,要求客户端发送认证信息 ngx.header['WWW-Authenticate'] = 'Basic realm="Restricted Area"' ngx.exit(ngx.HTTP_UNAUTHORIZED) else -- 不需要进行认证,继续处理请求 return end