在Ubuntu 18.04上使用Let’s Encrypt保护Nginx(2)

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
  /etc/letsencrypt/live/example.com/fullchain.pem
  Your key file has been saved at:
  /etc/letsencrypt/live/example.com/privkey.pem
  Your cert will expire on 2018-07-28. 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

现在您已拥有证书文件,您可以按如下方式编辑域服务器块:

/etc/nginx/sites-available/example.com

server {
    listen 80;
    server_name example.com;

include snippets/letsencrypt.conf;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name ;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    include snippets/ssl.conf;

return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

# . . . other code

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    include snippets/ssl.conf;

# . . . other code
}

通过上面的配置,我们强制HTTPS并从www重定向到非www版本。

最后,重新加载Nginx服务以使更改生效:

sudo systemctl reload nginx

SSL证书自动续订

让我们加密的证书有效期为90天。 要在证书过期之前自动续订证书,certbot软件包将创建一个每天运行两次的cronjob,并且将在证书到期前30天自动续订任何证书。

由于我们在证书更新后使用certbot webroot插件,我们还必须重新加载nginx服务。 将--renew-hook "systemctl reload reload"添加到/etc/cron.d/certbot文件中,使其看起来像这样:

/etc/cron.d/certbot

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --renew-hook "systemctl reload nginx"

要测试续订过程,您可以使用certbot --dry-run开关:

sudo certbot renew --dry-run

如果没有错误,则意味着更新过程成功。

就这样! 如果您遇到任何问题,请随时发表评论。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/edc680dca3ab37385727194544760598.html