根据具体的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 thenreturnendif res.status == 401 thenngx.status = res.statusngx.say(res.body)ngx.exit(401)endif res.status == 403 thenngx.say("haha 403")ngx.exit(ngx.HTTP_FORBIDDEN)endif res.status == 503 thenngx.exit(ngx.HTTP_METHOD_NOT_IMPLEMENTED)endngx.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 thenngx.status = ngx.HTTP_FORBIDDENngx.say("Access Denied")ngx.exit(ngx.HTTP_FORBIDDEN)returnend-- 如果用户已认证,则允许请求继续处理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" thenngx.var.backend = "http://xxxxx"end}proxy_pass $backend;break;
}