In an nginx config, I am trying to add a parameter which add a http request parameters. A x_user_id
is present as an http header, this should be added as a query parameter
http://somehost:8080/someurl?foo=bar
( Header x_user_id
1234
)
should be redirected to
http://otherhost?foo=bar&userId=1234
Also, if the user_id
parameter is present, it should be removed:
http://somehost:8080/someurl?foo=bar&userId=6666
( Header x_user_id
1234
)
should be redirected to
http://otherhost?foo=bar&userId=1234
Now I have seen the question Nginx Redirect - Remove a specific query parameter from URL , but it seems quite cryptic to do this in nginx. Also this document says that if is evil.
I have tried somethng like
if ($request_uri ~ "([^\?]*)\?(.*)?userId=([^&]*)[&]?(.*)") {
set $original_path $1;
set $args1 $2;
set $unwanted $3;
set $args2 $4;
set $args "";
proxy_pass https://httpbin.org/get?${args1}${args2} ;
}
but, first it is not working. It would probably be possible to get it to work, but it will probably be unmaintainable and quite cryptic.
I have also seen there is a module lua, and by using that, it seems to be easier and a more high-level programming model can be used like that:
local args = ngx.req.get_uri_args()
local headers = ngx.req.get_headers()
args.userId = nil -- remove user_id parameter
args.userId = headers.x_user_id
ngx.req.set_uri_args(args)
This seems well-readable for someone who is not familiar with nginx config. Unfortunately, lua is not included in vanilla nginx and therefore I can't use it.
How to do this is a manner which does not make the config files too cryptic?
Is nginx even the right place to do that?