access_by_lua nginx
根据具体的post json data 转发
location ~*\/api/v4/(objects|warning)(.*)/ {
access_by_lua '
local transfer_request_query = ngx.req.get_uri_args()
local res = ngx.location.capture("/auth_get", { args = transfer_request_query })
ngx.header.content_type = "application/json;charset=utf8"
local json = require "cjson";
if res.status == ngx.HTTP_OK then
return
end
if res.status == 401 then
ngx.status = res.status
ngx.say(res.body)
ngx.exit(401)
end
if res.status == 403 then
ngx.say("haha 403")
ngx.exit(ngx.HTTP_FORBIDDEN)
end
if res.status == 503 then
ngx.exit(ngx.HTTP_METHOD_NOT_IMPLEMENTED)
end
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
--ngx.exit(507)
';
验证函数
location /access-test {
access_by_lua_block {
-- 这里是Lua代码
ngx.log(ngx.INFO, "Entering access_by_lua_block")
-- 假设我们有一个变量表示用户是否已认证
local is_authenticated = check_user_authentication()
-- 如果用户未认证,则返回403 Forbidden响应
if not is_authenticated then
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say("Access Denied")
ngx.exit(ngx.HTTP_FORBIDDEN)
return
end
-- 如果用户已认证,则允许请求继续处理
ngx.log(ngx.INFO, "User is authenticated, allowing access")
}
# 其他Nginx配置...
# 例如,代理请求到后端服务器
proxy_pass http://backend_server;
}
# 假设check_user_authentication是一个在外部定义的Lua函数
# 它检查用户是否已认证,并返回布尔值
function check_user_authentication() {
-- 这里应该实现你的认证逻辑
-- 例如,检查HTTP头部、Cookie、JWT等
return true -- 假设用户已认证
end
具体转发
location ^~ /api/test{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Cookie $http_cookie;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Connection "";
set $backend "http://xxxx.server";
access_by_lua_block {
ngx.req.read_body()
local body = ngx.req.get_body_data()
local cjson = require "cjson"
local data = cjson.decode(body)
local gateway_id = data["gateway_id"]
if gateway_id == "xxxxxxx" then
ngx.var.backend = "http://xxxxx"
end
}
proxy_pass $backend;
break;
}
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/18766723