NGINX NAT/Proxying Gotcha

I recently had a problem with Dancer not redirecting correctly. I have 2 servers, running dev and live versions of my site NATted behind my router, and redirects from one were being sent to the other incorrectly.

    ( internet )       Connections come in to my.host.com on one of two ports
       |    |
    80 |    | 8080     Nothing below this must care about these port numbers
       |    |          which makes things fun, as location: headers need them
 [ NATting router ]
       |    |
    80 |    | 80       Servers sit on the default port, not knowing what's above
+live---+  +----dev+
| nginx |  | nginx |   location /myapp/ { proxy_pass http://localhost:5001; }
|- - - -|  |- - - -|
| plack |  | plack |   listens on the default port 5001
| - - - |  | - - - |
| myapp |  | myapp |   wants to do a redirect '/home' after a login, say
+-------+  +-------+   so I need the :8080 in the urls created on dev

The problem was that I had this in my nginx config for that location:

   proxy_set_header X-Forwarded-Host $host;
This fail because $host is just the host without the port

The solution was to replace that with this:

   proxy_set_header X-Forwarded-Host $http_host;
This works because $http_host includes the port, as it is extracted from the HTTP Host: header.


Another hastily constructed page by Phil Carmody
Home / linux / nginx_proxy.html