4

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

2 Answers 2

11

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).

Sign up to request clarification or add additional context in comments.

1 Comment

You can also have different settings for loggin, one for development and one for production, like this: // Settings for development app.configure('development', function(){ app.use(express.logger('dev')); }); // Settings for production app.configure('production', function(){ app.set('trust proxy', true); app.use(express.logger('default')); }); Then change your enviroment vars like this (Linux/Unix) NODE_ENV=production PORT=3000 node app.js Windows: SET NODE_ENV=production && SET PORT=3000 && node app.js
10

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"'));

1 Comment

Thank you so much for posting this. I found it via a Google search to solve the same problem I was having just now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.