6

Can proxy_pass work with variables? I am trying to make the below configuration work:

    http {
       ...

        map $http_user_agent $myvariable {
            default 'mobile';    

        }

       ...
    }

The location configuration:

server {
    listen       80;

   ...

    location /site {        
            proxy_pass http://docker-site/site/$myvariable;
        }

   ...
}

The configuration works if I replace the proxy_pass with http://docker-site/site/mobile;

Let me know if I am on the right track.

Syed Osama Maruf
  • 103
  • 2
  • 2
  • 9

1 Answers1

6

Those two cases are not the same. If you use a variable, that value will replace the entire URI.

In this case:

location /site { 
    proxy_pass http://docker-site/site/mobile;
}

the URI /site/foo is passed upstream as /site/mobile/foo.

To use your variable, you can use a rewrite (see this document for details):

location /site { 
    rewrite ^/site(.*)$ /site/$myvariable$1 break;
    proxy_pass http://docker-site;
}

Or a regular expression location:

location ~ ^/site(.*)$ {
    proxy_pass http://docker-site/site/$myvariable$1;
}

The evaluation order of regular expression location blocks is significant. See this document for details.

Richard Smith
  • 11,859
  • 2
  • 18
  • 26
  • thankyou for the prompt response. Using the rewrite one I am facing the error that `localhost redirected you too many times` if I try to access `localhost/site` where my server tries to redirect me to `localhost/site/login`. Although if I bypass the login then it works fine. Any idea? (P.S : I don't have enough rep to upvote this answer) – Syed Osama Maruf Oct 15 '18 at 08:14
  • this answer correctly explains the approach to tackle the above question. regarding the 302 bit i will ask a separate questions. thanks. – Syed Osama Maruf Oct 22 '18 at 13:20
  • Try `proxy_pass http://docker-site/site/$myvariable$uri` – ntg Jun 30 '21 at 15:55