Hi!
I think a transigent approach may can help you, you can use the error_page directive, like error_page 789 = @xxx
In your header_filter hook, check the condition and if you want to launch the redirect, you can use the ngx.exit(789) and let an internal redirect happens.
Then in your new location, you can do whatever you want.