nginx的同一个端口配置支持http与https协议

[root@VM-0-22-centos conf.d]# cat tx.qmgr.com.conf
upstream gatewayservice {
          server  127.0.0.1:8080  weight=1;
     }

server {

        listen       27800 ssl;
        server_name  tx.qmgr.com;                              #业务系统域名
        ssl_certificate /etc/nginx/cert/tx.qmgr.com.pem;       #业务系统域名证书公钥
        ssl_certificate_key /etc/nginx/cert/tx.qmgr.com.key;   #业务系统域名证书私钥
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        ssl_ciphers         HIGH:!aNULL:!MD5;


        set $redirectMode gatewayservice;

        location / {
               proxy_set_header Host $host:$server_port;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;

             #判断是https请求,就直接跳转,然后断开这个连接不希望往下执行

                if ($scheme = 'https') {
                  proxy_pass http://gatewayservice;     
                  break;
                }

#上面做了判断,所以现在是http访问,会跟下面location的@http_to_https进行关联

                try_files $uri $uri/ @http_to_https;  
                index  index.html index.htm;
        }

       location @http_to_https {
          proxy_set_header Host $host:$server_port;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_pass http://gatewayservice;
       }

#由于上面配置了ssl证书,如果你http访问,就会出现497报错,这个时候就直接跳转到上面的location的@http_to_https。相当于跳转https的请求。

        error_page 497 = @http_to_https;


        error_page 405 =200 $uri;
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
}

#测试http访问,

 #测试https访问

#测试成功,完美实现。 

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值