1

I am new to Nginx. As I know, we can configure proxy_pass url in nginx.conf like:

location /test
{
     proxy_pass http://10.10.10.10:10000;
}

But now, I need to proxy_pass to a variable url, we could get this url in http request header or request body(for example).

How could I implement this? Thanks for any help!

EDIT 1(explain my question):

There is a http request with a param named "redirectUrl" in its header send to Nginx, I just want Nginx modify this http request header and then send this request to the redirectUrl. Because the redirectUrl is a variable, so I guess "proxy_pass $request" can implement this, but I don't know how. Who can give me a hint or is there any documentation?

EDIT 2:

I tried ngx_lua :

location /apiproxytest {

    set_by_lua $redirectURL '
            return ngx.req.get_headers()["Host"]
    ';

    header_filter_by_lua '
             ngx.header["RedirectURL"] = nil;
             ngx.header["Host"] = nil;
    ';

    echo "1:" $redirectURL;

    set_by_lua $redirectURL2 '
            return ngx.req.get_headers()["Host"]
    ';

    echo "2:" $redirectURL2;

    #proxy_pass $redirectURL;
}   

I found that echo 1 and echo 2 were the same, as ngx.header.HEADER explains, ngx.header["Host"] = nil is supposed to remove Host in http request header. Why echo "2:" $redirectURL2 can also print the value of Host?

2
  • Have you read documentation? nginx.org/r/proxy_pass Commented May 20, 2015 at 11:07
  • @AlexeyTen thanks for your help, I had read the documentation, but it only tell me can, there is no how. Can you give me a hand? Commented May 21, 2015 at 2:13

1 Answer 1

1

Try ngx_lua.

Get redirectUrl from ngx.req.get_headers in set_by_lua, then set to something like $redirectURL, finally proxy_pass $redirectURL.

Append for Edit 2:

Why echo 1 and echo 2 were the same?

This is caused by Nginx Phases

set or set_by_lua is working at rewrite phase, echo is working at content phase, header_filter_by_lua is working at output-header-filter phase (doc), which is behind content.

Your config is worked like this:

set_by_lua -> set_by_lua -> echo 1 -> echo 2 -> header_filter_by_lua.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I have edited my new question of using ngx_lua. Please hlep me~
@SomnusLee I append my answer, wish to help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.