nginxhttp-redirectopenresty

nginx-openresty rewrite_by_lua_block and ngx.req.set_uri redirects to a file instead of location


I'm trying to use a rewrite in nginx-openresty following a simple example:

location /test 
{
   rewrite_by_lua_block { ngx.req.set_uri("/authgp") } 
}

location /authgp {
    proxy_pass http://authwf.org:9001/realms/gp/protocol/openid-connect/token;
}

When I invoke /test, nginx try to find a file named: [error] 35890#5234410: *1 open() "/opt/ho.../auth instead of forwarding to location /authgp as the example says.

How can I tell nginx-openresty not to try to resolve a file but a location?

Thanks! Fernando


Solution

  • TL;DR: use ngx.req.set_uri("/authgp", true) (add the second true argument)

    Explanation

    https://github.com/openresty/lua-nginx-module?tab=readme-ov-file#ngxreqset_uri

    syntax: ngx.req.set_uri(uri, jump?, binary?)

    The optional boolean jump argument can trigger location rematch (or location jump) as ngx_http_rewrite_module's rewrite directive[...]

    For example, the following Nginx config snippet

    rewrite ^ /foo last;
    

    can be coded in Lua like this:

    ngx.req.set_uri("/foo", true)
    

    Similarly, Nginx config

    rewrite ^ /foo break;
    

    can be coded in Lua as

    ngx.req.set_uri("/foo", false)
    

    or equivalently,

    ngx.req.set_uri("/foo")
    

    https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

    last

    stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;

    break

    stops processing the current set of ngx_http_rewrite_module directives as with the break directive; (Emphasis added)

    https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#break

    Syntax: break;

    Stops processing the current set of ngx_http_rewrite_module directives.

    If a directive is specified inside the location, further processing of the request continues in this location. (Emphasis added)

    Since you use set_uri inside the location block (location /test), with jump = false (the default value) “further processing of the request continues in this location.” (this location = the location /test block).