【经验/Notes】Nginx下使http协议和https协议共用一个端口

在Nginx下使http协议和https协议共用一个端口,使http自动301到https。我的测试机上是Tengine+bt面板,不过一样,均兼容。

1.打开你网站的配置文件,一般是nginx.conf(我的是已经配置好SSL的了):

server
{
 listen 80;
 listen 443 ssl http2;
 server_name jscdn.moeblog.top;
 index index.php index.html index.htm default.php default.htm default.html;
 root /www/wwwroot/jscdn; .........(下面省略)

然后修改以下代码:

    1. 删除配置正文第一行(实际是第3行)
      listen 80;
    2. 修改listen 443 ssl http2;为自己需要的端口,这里修改为4433
    3. server_name jscdn.moeblog.top;

      下面增加行

      ssl on;

      然后再回车换行,增加:

      error_page 497 https://$host:4433$request_uri;
      #注意: $host:后的端口根据需要自己进行修改,需要和上面ssl监听的保持一致

修改后的配置文件:

server
{
    listen 4433 ssl http2;
    server_name jscdn.moeblog.top;
    ssl on;
    error_page 497 https://$host:4433$request_uri;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/jscdn;
    .......(省略)

这样,http就和https共用4433端口,而且如果以http访问会自动跳转到https。

点赞
  1. 轻羽说道:
    听起来好棒
  2. amemb说道:
    Google Chrome Windows 10
    共用端口也没有优势呀。
    1. MoeWang说道:
      Google Chrome Android 9
      原来是家宽建站的时候用的,现在由于规定日趋严格不用了,作为一个参考吧。

回复 轻羽 取消回复

电子邮件地址不会被公开。必填项已用 * 标注