Grabbed the tutorial from
Pentropy.
Nginx 0.6.20 introduced the ability to use variables with the
proxy_pass directive. This seems like a rather small feature by itself, but it allows us to utilize the powerful map directive to better organize virtual hosting.
In our shared hosting configuration, we typically assign an entire internal IP address (127.0.0.1, 127.0.0.2, etc) to each client. This allows clients to map multiple ports to various applications (web apps, databases, etc) without too much concern about other users.
However, this can be difficult to keep in order since these addresses tend to get scattered across dozens of virtual host entries and include files in the Nginx configuration.
This is where map and using variables with the proxy_pass directive come in handy.
Here's a short example:
http {
resolver 127.0.0.1; # dns server
map_hash_max_size 4096; # needed if your hash table gets big
map $host $internal_ip {
hostnames;
.develix.com 127.0.0.2;
.twisty-industries.com 127.0.0.3;
.codemongers.com 127.0.0.4;
}
server {
server_name develix.com www.develix.com;
listen 198.145.247.210:80;
location / {
proxy_pass http://$internal_ip:8000$request_uri;
include /etc/nginx/proxy.conf;
}
}
server {
server_name twisty-industries.com www.twisty-industries.com;
listen 198.145.247.210:80;
location / {
proxy_pass http://$internal_ip:8000$request_uri;
include /etc/nginx/proxy.conf;
}
}
server {
server_name codemongers.com www.codemongers.com;
listen 198.145.247.210:80;
location / {
proxy_pass http://$internal_ip:8000$request_uri;
include /etc/nginx/proxy.conf;
}
}
server {
server_name wiki.codemongers.com;
listen 198.145.247.210:80;
location / {
proxy_pass http://$internal_ip:8001$request_uri;
include /etc/nginx/proxy.conf;
}
}
}
Note that while I could have put the port in the variable as well, this detracts from the flexibility, since each server section could conceivably utilize more than one port. It also tends to make the mapping less readable.
As you can see, the advantage of this approach is the ability to keep all the mappings in a single location, which is far easier to maintain.
Caveat: as of 0.6.20, the fastcgi_pass and
upstream directives do not support variables, although I expect this will change soon.