Search code examples
nginxproxyheaderhttp-proxy

Proxy a request - get a parameter from URL, add a header and update request URL using Nginx


I am looking for a way to do the following using Nginx:

  1. Intercept a request
  2. Read URL, parse it and read a value from it.
  3. Add that value as a new request header
  4. Update the URL (remove a particular value)
  5. Forward the request to another server

e.g

Request URL - http://<<nginx>>/test/001.xml/25
Final URL - http://<<server>>/test/001.xml with header (x-replica: 25)

I have a nginx server setup with a upstream for the actual server. I was wondering how do I setup Nginx to achieve this ?


Solution

  • Since the data exists within the request URI itself (available by the $uri variable in nginx), you can parse that using the nginx lua module. nginx will need to be compiled with lua for this to work, see: openresty's nginx lua module.

    From there you can use the set_by_lua_block or set_by_lua_file directive given $uri as a parameter.

    In configuration this would look something like:

    location / {
        ...
        set_by_lua_file $var_to_set /path/to/script.lua $uri;
        # $var_to_set would contain the result of the script from this point
        proxy_set_header X-Replica $var_to_set;
        ...
    }
    

    In script.lua we can access the $uri variable from in the ngx.arg list (see these docs):

    function parse_uri( uri )
        parsed_uri = uri
        -- Parse logic here
        return parsed_uri
    end
    
    return parse_uri( ngx.arg[1] )
    

    Similarly, you can modify this function or create another to make a variable with the updated $uri.