Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX as proxy of Node.js

I'm using NODE.js behind NGINX server, this is my Nginx configuration:

upstream example.it {
        server 127.0.0.1:8000;
}

server {
        server_name www.example.it;

        location / {
                proxy_pass      http://example.it;
                proxy_redirect  off;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
}

All works good, the requests are correctly sent from nginx to node BUT I saw a problem in the log file generated from Express.js.

The problem is that ALL THE REQUESTS are saved as done from 127.0.0.1, why?

I don't seen any remove hosts (the real ip of who made the request).

Thanks

like image 973
Dail Avatar asked Nov 30 '22 15:11

Dail


2 Answers

Assuming you're using Express 3.0, a better way to do this is through the trust proxy setting.

From the Express documentation:

trust proxy Enables reverse proxy support, disabled by default

In order to use it:

app.set('trust proxy', true);
app.use(express.logger('default'));

This has the added advantage of working correctly when you're using a proxy as when you're not (for example in a development environment).

like image 127
Andrew Newdigate Avatar answered Dec 05 '22 07:12

Andrew Newdigate


That's correct, as nginx will be the remote host. You need to specify a custom log format to log the X-Forwarded-For header, see the connect logger documentation.

app.use(express.logger(':req[X-Forwarded-For] - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'));
like image 40
Linus Thiel Avatar answered Dec 05 '22 09:12

Linus Thiel