0

I know there are Nginx phases. Why does the following snippet deliver the "200 Host: example.com" instead of forwarding to Google? What would be a generally valid workaround to evaluate Lua higher or before?

server
{
    listen 80;
    server_name example.com;

    location /
    {
        rewrite_by_lua_block
        {
            return ngx.redirect('https://www.google.com/', 303)
        }

        default_type text/plain;
        return 200 "Host: $host";
    }
}

Maybe this doesn't make sense at first sight, but I have an intelligent way to block/redirect certain calls in the Lua block (or in a Lua file included at this point). This module should work in general. With proxy_pass, alias etc. it works fine. Only with return 200 it does not work. Does anyone have an idea?

uav
  • 494
  • 3
  • 16

2 Answers2

1

https://github.com/openresty/lua-nginx-module#rewrite_by_lua

Note that this handler always runs after the standard ngx_http_rewrite_module.

So return 200 always executes before rewrite_by_lua_block.

In your case you should stick to rewrite_by_lua_block (didn't check)

if condition then
    return ngx.redirect('https://www.google.com/', 303)
else
    ngx.print("Hello");
    return ngx.exit(ngx.HTTP_OK)
end
Alexey Ten
  • 7,922
  • 31
  • 35
  • Thats not what I want - but thanks. – uav Aug 05 '20 at 10:03
  • @uav the question was “does anyone have an idea?”. I have. The answer is “you can't mix rewrite and lua modules and you can't evaluate lua before rewrite”. – Alexey Ten Aug 05 '20 at 13:46
  • @uav you could try to put your code into `access` phase. `ngx.redirect` should work there – Alexey Ten Aug 05 '20 at 13:48
  • Hey, that wasn't a critique, I just wrote the way it is. I'm very grateful for your help. Unfortunately access does not work either. – uav Aug 05 '20 at 18:09
0

Credits to Alexey Ten.


As an intermediate conclusion (until proven otherwise), instead of using Nginx code directly, I must implement return 200 in Lua.

        rewrite_by_lua_block {
            -- Will be executed. Can of course be combined with a condition.
            return ngx.redirect('https://www.google.com/', 303)
        }

        content_by_lua_block {
            ngx.header["Content-Type"] = "text/plain"
            ngx.print("Host: "..ngx.var.host)
            return ngx.exit(ngx.HTTP_OK)
        }

This is not what I want, but I had asked for a workaround. If anyone has a better one, go ahead.

uav
  • 494
  • 3
  • 16