Nginx特定端口同时监听http和https

方案出自 Sam Bull :https://serverfault.com/a/930789

一般来说http占用80端口,https占用443端口,是分开的。

假如你想整个567端口,同时监听http和https,那么:

首先在site-enabled网站的配置文件中按常态监听两个端口:

listen 80;

listen [::]:80;

listen 443 ssl;

listen [::]:443 ssl;

然后在nginx.conf中,http段的下面,加入一个新的stream段:

stream {

    upstream http {

        server localhost:80;

    }

    upstream https {

        server localhost:443;

    }

    map $ssl_preread_protocol $upstream {

        default https;

        "" http;

    }

    server {

        listen 567;

        listen [::]:567;

        proxy_pass $upstream;

        ssl_preread on;

    }

}

这段的意思是,监听567端口,并且在收到请求时,分流至localhost对应的http或https端口。

1