Nginx同端口下的http重定向https

615 阅读1分钟

1、问题来源

因为使用政务云,他们网络安全要求无法使用80和443这俩默认端口。我们的网站端口使用的是8080端口,并配置了ssl。

    server {
        listen       8080 ssl;
        server_name  localhost;

        ssl_certificate      cert/cert.pem;
        ssl_certificate_key  cert/cert.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

该在http协议的场景下访问网站会报错。 http://ip:8080/api 如下图
强迫比较难受就想把http重定向到https

image.png

2、解决方案

利用error_page 497重定向到https
配置内容 error_page 497 https://host:8080host:8080uri?$args; 下方是完整配置

server {
        listen       8080 ssl;
        server_name  localhost;

        ssl_certificate      cert/cert.pem;
        ssl_certificate_key  cert/cert.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page  497              https://$host:8080$uri?$args;
        error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

3、收工