How to configure nginx so it works with Express?

Posted by Michal Stefanow on Server Fault See other posts from Server Fault or by Michal Stefanow
Published on 2014-06-02T23:58:22Z Indexed on 2014/06/03 3:30 UTC
Read the original article Hit count: 488

I'm trying to configure nginx so it proxy_pass requests to my node apps. Question on StackOverflow got many upvotes: http://stackoverflow.com/questions/5009324/node-js-nginx-and-now and I'm using config from there.

(but since question is about server configuration it is supposed to be on ServerFault)

Here is the nginx configuration:

server {
  listen 80;
  listen [::]:80;

  root /var/www/services.stefanow.net/public_html;
  index index.html index.htm;
  server_name services.stefanow.net;

  location / {
    try_files $uri $uri/ =404;
  }

  location /test-express {
    proxy_pass    http://127.0.0.1:3002;
  }    

  location /test-http {
    proxy_pass    http://127.0.0.1:3003;
  }
}

Using plain node:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3003, '127.0.0.1');

console.log('Server running at http://127.0.0.1:3003/');

It works! Check: http://services.stefanow.net/test-http

Using express:

var express = require('express');
var app = express(); //

app.get('/', function(req, res) {
  res.redirect('/index.html');
});

app.get('/index.html', function(req, res) {
  res.send("blah blah index.html");
});

app.listen(3002, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3002/');

It doesn't work :( See: http://services.stefanow.net/test-express


I know that something is going on.

a) test-express is NOT running enter image description here

b) text-express is running

enter image description here

(and I can confirm it is running via command line while ssh on the server)

root@stefanow:~# service nginx restart
 * Restarting nginx nginx                                                                                  [ OK ]

root@stefanow:~# curl localhost:3002
Moved Temporarily. Redirecting to /index.html

root@stefanow:~# curl localhost:3002/index.html
blah blah index.html

I tried setting headers as described here: http://www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/ (still doesn't work)

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;

I also tried replacing '127.0.0.1' with 'localhost' and vice versa


Please advise. I'm pretty sure I miss some obvious detail and I would like to learn more. Thank you.

© Server Fault or respective owner

Related posts about nginx

Related posts about reverse-proxy