Using map and proxy_pass

Francis Daly francis at daoine.org
Mon May 2 19:35:31 MSD 2011


On Mon, May 02, 2011 at 02:56:19PM +0200, Markus Jelsma wrote:

Hi there,

A general rule for most config confusions is "the debug log is your
friend".

> Anyone else having some thoughs on how to use the map in conjunction with 
> proxy_pass to set different hosts based on the first URI segment?

It's not clear to me why you're happy to generate an include file of
mappings in an external program, but not happy to generate an include
file of locations in an external program.

And if you have a large number of locations, you'll probably be happier
having no top-level regex locations.

But all that aside...

"map $var1 $var2" sets $var2 based on a string match of $var1.

You wish to match based on the first uri segment. So, do just that:

===
http {
  map $first_segment $value {
      default     127.0.0.1;
      /abc        127.0.0.2;
      /def        127.0.0.3;
  }
  server {
    if ($uri ~* ^(/[^/]*) ) {
      set $first_segment $1;
    }
    location / {
      proxy_pass http://$value:8080/$uri ;
    }
  }
}
===

You may want to play with the proxy_pass line depending on exactly what
you want to do, but the above seems to work for me.

You can also add a $second_segment (or $part2) in the if{} block, if
you want a separate map for that.

Good luck with it,

	f
-- 
Francis Daly        francis at daoine.org



More information about the nginx mailing list