Nginx IMAP proxy

Nginx seems to be a quite versatile server with some interesting features. One of them is the functionality of working as an IMAP proxy / SMTP proxy / POP3 proxy. There are several ways to implement this in the configuration. This example will show a way to make the authentication of the IMAP proxy without needing to use CGI application to process users’ data.

The configuration should be self-explanatory. However, difficulties arise, feel free to contact us on our contact us page.

The authentication part in the main configuration:

http {
	    map $http_auth_user $pstatus {
	      "$" OK;
	        default	Invalid;
	    map $http_auth_user $pserver {
	        default	Invalid;
	    map $http_auth_protocol $pport {
	      imap		22143;
	      pop3		22110;
	      smtp		22025;
	        default	Invalid;

The nginx built in engine has the ability to process regular expressions. This feature is used here for checking the incoming username for authentication. The authenticated connection gets fowarded to appropriate port on localhost. Now we have to assign /auth to allow incoming authentication request, we can use this example:

    server {
        listen       80 default_server;
        server_name  _;

        location @gossl {
                return  301 https://$host$request_uri;

        location = /auth {
            error_page 403 = @gossl;
            if ($remote_addr != {
                return 403;
                add_header Auth-Status $pstatus;
                add_header Auth-Server $pserver;
                add_header Auth-Port   $pport;
                return 204;

To enable the imap/smtp/pop3 server:

load_module "modules/";
mail {
  proxy  on;
  proxy_pass_error_message on;
  proxy_smtp_auth on;
  xclient off;
  imap_auth plain login;
  pop3_auth plain apop;
  smtp_auth plain login;
  imap_capabilities "IMAP4rev1"; 
  pop3_capabilities "TOP" "USER";

ssl_certificate /etc/letsencrypt/live/...../fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/...../privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

server {
    listen      143;
    listen	993 ssl;
    protocol    imap;
    starttls    on;
    auth_http_header User-Agent "Nginx IMAP4 proxy";
server {
    listen      110;
    listen	995 ssl;
    starttls    on;
    protocol    pop3;
    pop3_auth   plain;
    auth_http_header User-Agent "Nginx POP3 proxy";
server {
    listen 25;
    listen 587;
    listen 465 ssl;
    starttls on;
    protocol smtp;
    auth_http_header User-Agent "Nginx SMTP proxy";
    timeout 12000;

Note: SSL configuration should be done per your own setting. The scope of this example does not cover this part. Also, make sure points to your server.

For more details, please checkĀ guide.

You can see other guides and documents of on Blog page as well as our Rambkk Github page