How to forward requests with proxy_pass in nginx

I’ve been doing some work of late with The Green Web Foundation, and recently we moved from using Gearman as a queue, to RabbitMQ instead.

RabbitMQ has a management UI that makes it easier to tell what it’s doing, and it also exposes this information at a specific port, (lets say 12345) in the form of a handy dashboard.

You might want to make this easy to see remotely, and if you already use Nginx as a webserver for serving files on the same machine, one thing you can do is serve this dashboard using nginx, using a handy directive called proxy_pass, and setting up an upstream provider, to send requests to another service.

Here’s how it works.

First all, set up a server

server {
  # sample values
  listen 123.123.123.123:80;
  server_name dashboard.thegreenwebfoundation.org;
  # the directory to serve files from
  root  /var/www/dashboard.thegreenwebfoundation.org;


  location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.html$is_args$args;
  }

}

Once you have a server, this should be serving files from the directory /var/www/dashboard.thegreenwebfoundation.org.

This works for static files, but in the case of the RabbitMQ dashboard, we have the dashboard being served from a different port.

One way to serve this content on a different port is to define it as an upstream, server, like so, so we can refer to it later:

upstream rabbitmgmnt {
	server localhost:12345;
}

Now we have defined a server listening on 12345, we need a way to send traffic along to this new upstream server. One way is to use the location directive like this – now, any requests sent to dashboard.thegreenwebfoundation.org/rabbit will not be sent along to the upstream rabbitmgnt server.

location /rabbit/ {
        proxy_pass http://rabbitmgmnt/;
  }

Why is this useful?

This is handy as it saves you needing to set up a whole new virtual host.

Note: I’ve abridged the code this example to keep the code easily readable, but you’d almost always serve this over HTTPS, and ideally, you’d try to reduce the possible IP addresses you’ve be able to access this endpoint over.

This post is one for my future self, when I forget how to use nginx again…

Helpful links

RabbitMQ Management plugin – https://www.rabbitmq.com/management.html

Nginx proxy_pass info – http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

Nginx upstream servers – http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream