Nginx mail proxy hides client's ip

Solution 1:

Workaround

Not finding suitable solution I rather created a new log file in the proxy script which provided a acceptable solution to the request.

Here is the excerpt:

$fp = fopen('/var/log/mail_logins.log', 'a');
$now = "[" . (new \DateTime())->format('Y-m-d H:i:s') . "]";
fwrite($fp, $now . " HTTP_AUTH_PROTOCOL: " . $_SERVER["HTTP_AUTH_PROTOCOL"] . ", HTTP_AUTH_USER: " . $_SERVER["HTTP_AUTH_USER"] . ", HTTP_CLIENT_IP: " . $_SERVER["HTTP_CLIENT_IP"]. "\n");
fclose($fp);

It might help someone.

Solution 2:

Since version 1.19.8 (released 09 Mar 2021), nginx supports HAproxy's proxy protocol for all POP3/IMAP/SMTP proxied connections - you can enable it by setting proxy_protocol on; in relevant server or mail block. Link to the nginx docs.

Note that proxy protocol must be explicitly enabled on the receiving end (in dovecot), since it can't be auto-detected (in mail protocols, it's server who sends greeting message after connection is established, and if client speaks before the server - it's a protocol violation; while in HAproxy's proxy protocol it's the client (i.e. proxy connecting to the final server) who first sends the message about remote connection).

Also note that this question was asked ~4 years before this option was added, but to anyone looking for this in the future this information might be useful.