nginx配置自签名的ssl证书(轻松实现https连接)

自签名的证书比较适合于加密接口请求的访问,如果是web端https连接的话,最好是用公证机构提供的证书。
另外,自2017年1月1日起,苹果会强制ios应用使用https方式连接

生成自签名证书

脚本具体代码如下(有部分修改):根据需求也可以自行修改脚本代码,比如有效时长等等

#!/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
service nginx restart

最后一定要去阿里云的安全组开放443端口,操作和开放80端口方法是一样的。 

你可能感兴趣的:([TechOps],nginx,ssl,安全)