SoFunction
Updated on 2025-03-04

How to forward nginx to different addresses according to fields in the message

nginx receives a post request. The request message is a json string, and there is a field id in the string.
Depending on the id, forward to different addresses.
If id=aaa, forward to
If id=bbb, forward to
How to configure, please provide a

To be in JSON load based on POST request in NginxidThe value of the field is forwarded, you can use Nginx'sngx_http_lua_moduleModule, This module allows you to use Lua scripts in Nginx configuration. Here is a sample configuration that shows how to do a JSON load based on a POST requestidThe value of the field to forward the request.

First, make sure your Nginx is installedlua-nginx-moduleandlua-resty-httplibrary. These can be installed through OpenResty, an Nginx distribution that integrates commonly used modules.

Install OpenResty

You can install OpenResty with the following command (assuming you are using a Debian-based system, such as Ubuntu):

sudo apt-get update
sudo apt-get install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring
curl -O /package/
sudo apt-key add 
sudo apt-get install -y apt-transport-https
echo "deb /package/debian $(lsb_release -sc) openresty" | sudo tee /etc/apt//
sudo apt-get update
sudo apt-get install -y openresty

Nginx configuration ()

Here is an exampleconfig, which uses Lua scripts to parse the JSON load requested by POST and according toidThe value of the field forwards the request.

http {
    lua_package_path "/usr/local/openresty/luajit/share/lua/5.1/?.lua;;";
    lua_shared_dict my_cache 10m;
    server {
        listen 80;
        location / {
            content_by_lua_block {
                -- Read POST Request body
                .read_body()
                local data = .get_body_data()
                if not data then
                     = ngx.HTTP_BAD_REQUEST
                    ("No request body found")
                    return (ngx.HTTP_BAD_REQUEST)
                end
                -- Analysis JSON
                local cjson = require ""
                local json_data = (data)
                if not json_data or not json_data.id then
                     = ngx.HTTP_BAD_REQUEST
                    ("Invalid JSON or missing 'id' field")
                    return (ngx.HTTP_BAD_REQUEST)
                end
                local id = json_data.id
                local target_url
                if id == "aaa" then
                    target_url = ""
                elseif id == "bbb" then
                    target_url = ""
                else
                     = ngx.HTTP_NOT_FOUND
                    ("Unknown 'id' value")
                    return (ngx.HTTP_NOT_FOUND)
                end
                -- create HTTP Client and forward request
                local http = require ""
                local httpc = ()
                local res, err = httpc:request_uri(target_url, {
                    method = .request_method,
                    body = data,
                    headers = .get_headers(),
                    keepalive = false,
                })
                if not res then
                     = ngx.HTTP_INTERNAL_SERVER_ERROR
                    ("Failed to forward request: ", err)
                    return (ngx.HTTP_INTERNAL_SERVER_ERROR)
                end
                -- Set the response header
                for k, v in pairs() do
                    [k] = v
                end
                -- Send a response body
                 = 
                ()
                -- closure HTTP Client
                httpc:close()
            }
        }
    }
}

explain

  • lua_package_path and lua_shared_dict: Sets the search path and shared dictionary for the Lua module.
  • server and location: define a server block and a location block to handle incoming requests.
  • content_by_lua_block: Use Lua script to handle requests.
  • .read_body(): Reads the POST request body.
  • (data): parses JSON data.
  • Conditional judgment: Determine the target URL based on the value of the id field.
  • : Create an HTTP client using the module and forward the request.
  • Set response header and status: Pass the response header and status code of the target server to the client.
  • Send response body: Send the response body of the target server to the client.

Make sure you have installed itlua-cjsonandlua-resty-httplibrary, which is usually included when using OpenResty. If you manually install Nginx and Lua modules, you need to make sure these libraries are available.

Restart Nginx

After modificationAfter that, don't forget to restart Nginx to apply the new configuration:

sudo systemctl restart nginx

This way, Nginx will be able to use the JSON load in the POST requestidThe value of the field to forward the request.

This is the article about nginx forwarding to different addresses according to fields in the message. For more related nginx forwarding to different addresses according to fields in the message, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!