又一篇利用 Let's Encrypt 配置 https

少说废话,上操作,环境基础 centos7 + nginx,通过 yum 安装 letsencrypt

sudo yum install letsencrypt  

生成 ssl 证书文件

 sudo letsencrypt certonly --standalone --email yourself@email.com -d yourself.cn 
这里注意 --standalone 参数, 需要停止 nginx 服务,让出 80 端口

出现如下提示表示证书顺利生成


- IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
  /etc/letsencrypt/live/yourself.cn/fullchain.pem
  Your key file has been saved at:
  /etc/letsencrypt/live/yourself.cn/privkey.pem
  Your cert will expire on 2019-01-01. To obtain a new or tweaked
  version of this certificate in the future, simply run certbot
  again. To non-interactively renew *all* of your certificates, run
  "certbot renew"
- Your account credentials have been saved in your Certbot
  configuration directory at /etc/letsencrypt. You should make a
  secure backup of this folder now. This configuration directory will
  also contain certificates and private keys obtained by Certbot so
  making regular backups of this folder is ideal.
- If you like Certbot, please consider supporting our work by:

  Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
  Donating to EFF:                    https://eff.org/donate-le
这两句是关键后面配置 nginx 需要用到 \
/etc/letsencrypt/live/yourself.cn/fullchain.pem \
/etc/letsencrypt/live/yourself.cn/privkey.pem

配置 nginx 监听 443 端口


server {
  listen       443 ssl;
  server_name  yourself.cn;

  ssl on;
  ssl_certificate      /etc/letsencrypt/live/yourself.cn/fullchain.pem;
  ssl_certificate_key  /etc/letsencrypt/live/yourself.cn/privkey.pem;
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;

  location / {
    root   /var/www;
    index  index.html index.htm index.php;
  }

  location ~ \.php$ {
    root           /var/www;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
  }
}

把 http 访问重定向到 https


server {
  listen       80;
  server_name  yourself.cn;
  return 301 https://yourself.cn$request_uri;
}

证书有效期只有 90 天,通过定时任务设置自动更新,这里推荐一个 crontab 验证工具


sudo touch filename.sh # 创建执行脚本文件 写入以下命令
sudo systemctl stop nginx && certbot renew  && systemctl start nginx

crontab -e # 编辑定时任务
0 0 1 */2 * /path/filename.sh  # 两个月更新一次

验证操作


crontab -l # 查看定时任务
sudo certbot renew --dry-run # 该命令可以模拟更新证书 (记得先关掉 nginx )
sudo openssl x509 -noout -dates -in /etc/letsencrypt/live/yourself.cn/cert.pem # 查看证书有效期

重启 nignx 访问 网站 收工。

文档信息
发表日期:2019-05-22