1、准备证书

方式一、阿里云签名证书

mkdir -p /usr/local/nginx/cert

wget -o /usr/local/nginx/cert/5492579_www.kxy.cn_nginx.zip url_to_5492579_www.kxy.cn_nginx.zip

unzip 5492579_www.kxy.cn_nginx.zip

mv 5492579_www.kxy.cn_nginx.key /usr/local/nginx/cert/cert.key

mv 5492579_www.kxy.cn_nginx.pem /usr/local/nginx/cert/cert.pem

方式二、使用自签名证书

htpasswd 工具生成自签名证书,参考:SSL自签名证书 - https
可使用crt证书替代pem证书
配置Docker安装的Nginx时注意证书路径

2、配置server标签

server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /usr/local/nginx/cert/cert.pem;
        ssl_certificate_key  /usr/local/nginx/cert/cert.key;

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

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

				#反向代理多个内部http服务
        location /context_path {
                proxy_pass http://127.0.0.1:8080/context_path;
                proxy_redirect default;
        }
    }
    
# 注意:很多时候,访问一个网站的时候不会刻意去加https开头,而是直接输入域名访问,但是这样浏览器默认是http请求,如何让用户直接输入域名访问的也是https请求呢?

# 方法1:将所有http请求重定向到https
server { 
        charset utf-8;
        listen 80; 
        server_name 你的域名;
        rewrite ^(.*) https://$host$1 permanent;
    }
    
# 方法2:当网站只允许https访问的时候,通过http访问会报497状态码,利用error_page的方式重定向到https
server {
        listen       443 ssl;
        listen       80;
        server_name  localhost;
        charset utf-8;

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

        error_page 497  https://$host$uri?$args;
    }

# 方法3:利用浏览器的方式 首先,建一个html文本,命名为https.html
<html>  
<meta http-equiv="refresh" content="0;url=https://你的域名/">  
</html>
#其次,再通过配置监听80端口的server对该html访问:
server { 
        charset utf-8;
        listen 80; 
        server_name 你的域名;
        location / {
            root html;
            index https.html;
        }
        error_page 404 https://你的域名/;
    }

注意

启动Nginx时如果报“parameter requires ngx_http_ssl_module”的问题,则需要配置https模块后,重新make源文件
参考链接:https://my.oschina.net/litengteng/blog/1800751
https://blog.csdn.net/qq_33326449/article/details/104925644

Q.E.D.


行走在天地间自由的灵魂