nginx(openresty) lua 解决对接其他平台,响应文件中地址跨域问题

location 添加配置

复制代码
# location  添加的配置
# 作用:清空body体中的内,使得在lua处理响应体是,重新计算返回大小【如果不置空,它会保留原始响应体大小,导致处理数据的时候出现截断的问题】
header_filter_by_lua 'ngx.header.content_length = nil';
# 配置指定使用的lua脚本
body_filter_by_lua_file conf/lua_script/response.lua;

lua脚本文件

复制代码
#response.lua;脚本内容
-- 获取当前响应数据
local chunk, eof = ngx.arg[1], ngx.arg[2]

-- 定义全局变量,收集全部响应
if ngx.ctx.buffered == nil then
    ngx.ctx.buffered = {}
end

-- 如果非最后一次响应,将当前响应赋值
if chunk ~= "" and not ngx.is_subrequest then
    table.insert(ngx.ctx.buffered, chunk)

    -- 将当前响应赋值为空,以修改后的内容作为最终响应
    ngx.arg[1] = nil
end

-- 如果为最后一次响应,对所有响应数据进行处理
if eof then
    -- 获取所有响应数据
    local whole = table.concat(ngx.ctx.buffered)

    ngx.ctx.buffered = nil

    if not whole then
        ngx.log(ngx.NOTICE, "Response-Response Body Is Null: ", whole)
        return
    end

    -- 进行你所需要进行的处理
    ngx.log(ngx.NOTICE, "Response-Digest Business Param String: ", whole)

    --原始地址
    local str ="1.8.2.3:8084"
    --新地址
    local str1 = "10.14.65.129:9901"
    -- string.gsub(whole,str,str1)
    -- 重新赋值响应数据,以修改后的内容作为最终响应
    ngx.arg[1] = string.gsub(whole,str,str1)
end

场景:

在原有的平台,外挂三方的链接,三方只对服务ip开通访问权限,所有客户端访问都失败,现在采用所有访问三方的地址,都改为服务端的地址,通过服务端地址代理解决这个问题。也就是将1.8.2.3:8084替换为服务器ip10.14.65.129,然后通过nginx或者openresty代理区解决

相关推荐
小马爱打代码3 小时前
Nginx+Lua+Redis实现灰度发布
redis·nginx·lua
秉承初心4 小时前
Nginx核心原理以及案例分析(AI)
运维·nginx
Hello.Reader16 小时前
用 NGINX 打造高性能 FastCGI 加速 `ngx_http_fastcgi_module`
运维·nginx·http
澜兮子20 小时前
Nginx安全防护与HTTPS部署
nginx·安全·https
Lw老王要学习1 天前
25_05_02Linux架构篇、第1章_03安装部署nginx
linux·运维·nginx·架构·云计算·it
程序猿多布1 天前
Lua 元表和元方法
lua
程序猿多布1 天前
Sublime Text快速搭建Lua语言运行环境
lua·sublime text
Hello.Reader2 天前
NGINX `ngx_http_auth_request_module` 模块详解基于子请求的认证授权方案
运维·nginx·http
lml48562 天前
Nginx安全防护与HTTPS部署实战
nginx·安全·https
惊起白鸽4502 天前
nginx安全防护与HTTPS部署实战
nginx·安全·https