创建gencert.sh脚本文件

#!/bin/sh
 
# create self-signed server certificate:
 
read -p "Enter your domain [www.example.com]: " DOMAIN
 
echo "Create server key..."
 
openssl genrsa -des3 -out $DOMAIN.key 1024
 
echo "Create server certificate signing request..."
 
SUBJECT="/C=US/ST=Mars/L=iTranswarp/O=iTranswarp/OU=iTranswarp/CN=$DOMAIN"
 
openssl req -new -subj $SUBJECT -key $DOMAIN.key -out $DOMAIN.csr
 
echo "Remove password..."
 
mv $DOMAIN.key $DOMAIN.origin.key
openssl rsa -in $DOMAIN.origin.key -out $DOMAIN.key
 
echo "Sign SSL certificate..."
 
openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt
 
echo "TODO:"
echo "Copy $DOMAIN.crt to /etc/nginx/ssl/$DOMAIN.crt"
echo "Copy $DOMAIN.key to /etc/nginx/ssl/$DOMAIN.key"
echo "Add configuration in nginx:"
echo "server {"
echo "    listen 443 ssl"
echo "    ..."
echo "    ssl on;"
echo "    ssl_certificate     /etc/nginx/ssl/$DOMAIN.crt;"
echo "    ssl_certificate_key /etc/nginx/ssl/$DOMAIN.key;"
echo "    ssl_protocols   TLSv1 TLSv1.1 TLSv1.2"
echo "    ssl_ciphers     HIGH:!aNULL:!MD5"
echo "}"

生成证书

# 根据提示输入域名和四次口令(四次口令输入内容相同,须同时包含字母和数字
sh ./gencert.sh

Nginx配置

# 复制证书至/etc/nginx/ssl目录
cp www.test.com.crt  /etc/nginx/ssl/www.test.com.crt
cp www.test.com.key  /etc/nginx/ssl/www.test.com.key
 
 
# 修改nginx的server配置
server {
    #监听80端口,强制转到443端口,进行https访问
    listen  80;
    server_name test.cn;
 
    rewrite ^(.*)$  https://$host$1 permanent;
}
server {
    listen  443 ssl;
 
    #强制使用https访问
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains;preload" always;
 
    ...# 此处省略其它配置内容
 
    ssl on;
    ssl_certificate     /etc/nginx/ssl/www.test.com.crt; #证书格式有多种,常见的有pem、cer等
    ssl_certificate_key /etc/nginx/ssl/www.test.com.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
}
 
# 测试Nginx配置是否正确
nginx -t 

# 启动Nginx
systemctl start nginx

# 如果Nginx已启动,以下方式二选一
# 重载Nginx配置文件
nginx -s reload

# 重启Nginx服务
systemctl restart nginx

PS:如果是云服务器记得在服务器安全组开放443端口