Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx - Passing request header variables to upstream URL as query parameter

I have an application running on localhost listening on port 8080

nginx is running as reverse proxy, listening on port 80

So, a request coming to nginx on port 80 is sent to this application listening on localhost:8080 and response from this application sent back to the user

Now this application is incapable of reading the header variables from request header and can read only query parameters

So I want nginx to pass header values as query parameters to this application listening on localhost:8080

E.g. let us say in the request header there is a custom variable called 'userid'.

How do we pass this userid as &userid=value appended to the url to application listening on localhost 8080

My current test file of site-available and site-enabled is

server {

    location /test {

        proxy_pass http://localhost:8080;
    }

}
like image 431
Tahseen Avatar asked Mar 03 '19 02:03

Tahseen


2 Answers

So there is no need to do rewrite or anything else. Simply pass the header parameters that you want to pass as query parameter to the localhost application like below by appending to the arguments.

If you have custom header parameter like userid, then it would be $http_userid

server {

    location /test {

          set $args $args&host=$http_host;

          proxy_pass http://localhost:8080;
    }
 }
like image 84
Tahseen Avatar answered Oct 06 '22 00:10

Tahseen


If you have a request header called userid, it will be available within an Nginx variable called $http_userid.

You can alter the query parameters of the original request with a rewrite...break statement.

For example:

location /test {
    rewrite ^(.*)$ $1?userid=$http_userid break;
    proxy_pass http://localhost:8080;
}

See this document for details.

like image 28
Richard Smith Avatar answered Oct 06 '22 02:10

Richard Smith