大网数据广告活动
服务器运维问答

Nginx listen on any port but rewrite on 8080

· 52CE 我爱测

I have set up an nginx proxy with Openresty. The proxy takes up an HTTP SOAP POST request , modifies it by using a LUA script written within the root location ("/") of the HTTP server on port 8080, and sends it to a backend serve…

问题原文

原帖链接 · Alessandro · CC BY-SA 4.0

I have set up an nginx proxy with Openresty. The proxy takes up an HTTP SOAP POST request, modifies it by using a LUA script written within the root location ("/") of the HTTP server on port 8080, and sends it to a backend server for processing, which works correctly.

When the proxy relays the connection to the backend server, it creates a new connection, as per TCP specs, generating a new source port different from port 8080, where the backend server should respond.

Is there a way to intercept the response on nginx, so that it'll be able to intercept such response and modify it accordingly, with a LUA script?

Thanks for any insights you may be able to provide.

已采纳解答

原帖链接 · Ivan Shatsky · CC BY-SA 4.0

Here is the example based on my previous answer:

    location / {
        access_by_lua '
            ngx.req.read_body()
            local body = ngx.req.get_body_data()
            body = string.gsub(body, "_v4", "_v2")
            ngx.req.set_body_data(body)
            local header = ngx.req.get_headers()["Content-Type"]
            header = string.gsub(header, "_v4", "_v2")
            ngx.req.set_header("Content-Type", header)
        ';
        proxy_pass http://192.168.1.3:1234;
        body_filter_by_lua '
            # getting response body
            local body = ngx.arg[1]
            # response body is in a "body" variable now
            # do some modifications with "body" variable
            # just an example: convert body to uppercase
            body = string.upper(body)
            # setting back modified response body
            ngx.arg[1] = body
        ';
    }

If your response body is large enough, things can be more complicated because response processed by parts (by data chunks in nginx terminology).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-12-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。