March 12th, 2011

Proxying node.js with nginx

Sometimes you might want to run nginx in front of node.js in order to serve static content or proxy requests to several node instances.

Here's how you do it (/etc/nginx/conf.d/virtual.conf):

upstream node_blog {
    server 127.0.0.1:12000;
}

server {
    listen      80;
    server_name example.com www.example.com;

    access_log /var/log/nginx/example.access.log;

    root /path/to/docroot/public;

    location ~ /(images|stylesheets|javascripts) {        
        expires max;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://node_blog/;
        proxy_redirect off;
    }
}

In this example, the node server is running on port 12000 of the localhost. I'm serving the static content with nginx and everything else is proxied to node.

You can add several upstream blocks, one for each node instance. The main idea is using proxy_pass to proxy the request to node.