Sunday, April 3, 2011

timbit! nginx and node.js side-by-side

Scenario: you want to try out node.js but you're wondering how to serve up static files from it.

Answer: nginx is already a fast, light webserver.  Use that as your static file server and use it as a proxy for your node.js server.

/etc/nginx/conf/nginx.conf

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    upstream nodejs_node {
        server 127.0.0.1:3000;
    }

    server {
        listen       80;
        server_name  localhost;

        location /s {
            root /srv/http/static;
            index  index.html index.htm;
        }

        location / {
            root   html;
            index  index.html index.htm;

            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://nodejs_node/;
            proxy_redirect off;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

Static files:
You can see above that any URI's with /s are rooted in /srv/http/static.  So if a browser goes to http://localhost/s/ext-3.2.1/ they will be served files from /srv/http/static/s/ext-3.2.1.

Dynamic node.js files:
I run node with meryl, which defaults to port 3000 and that's good enough for me.  So any URI's that don't resolve to /s will be proxied to localhost:3000.

1 comment:

  1. pretty cool. I was starting to read about nginx this weekend as well.

    ReplyDelete