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代理区解决

相关推荐
郝亚军6 小时前
使用Vue 3和Nginx打包和部署Vue.js项目的一般步骤
前端·vue.js·nginx
星空露珠7 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
難釋懷14 小时前
Nginx代理https请求
redis·nginx·https
chexus2 天前
21. 深入 Nginx HTTP 缓存源码:CDN功能
nginx·http·缓存
BelongPanda2 天前
Linux Nginx 纯手动 Let‘s Encrypt 泛域名证书配置教程
linux·nginx
郝亚军3 天前
nginx的三个基础库:PCRE、OpenSSL、Zlib的安装
linux·服务器·nginx
CodexDave3 天前
MySQL事务隔离级别与MVCC机制解析
前端·数据库·mysql·nginx·性能优化·负载均衡
chexus4 天前
20. 深入 Nginx 信号处理
linux·c语言·网络·nginx
名字还没想好☜4 天前
Nginx 反向代理与负载均衡配置实战
运维·nginx·负载均衡