如何在 Ubuntu 16.04/18.04 上使用 Apache2 安装 Let’s Encrypt

介绍

使用 SSL 来保护您的网站对于 数据安全、用户信任以及 SEO 排名 都至关重要。
Let’s Encrypt 提供了一个免费、自动化、开放的证书颁发机构(CA),让您能够轻松安装和配置 SSL 证书。

在本指南中,我们将逐步讲解如何在 Ubuntu 16.04/18.04 系统中,使用 Apache2 设置 Let’s Encrypt SSL 证书。

前提条件

在开始之前,请确保您具备以下条件:

  • 一台运行 Ubuntu 16.04 或 Ubuntu 18.04 的服务器。
  • 一个已注册的域名,并且已指向服务器的公网 IP。
  • 已安装并运行 Apache2
  • 拥有服务器的 sudo/root 权限

在 Ubuntu 16.04/18.04 上使用 Apache2 安装 Let’s Encrypt 的步骤

步骤 1:更新系统

通过 SSH 以 root 用户身份登录您的 Ubuntu 16.04/18.04 服务器:

ssh root@IP_Address -p Port_Number

确保您的系统已完全更新:

apt-get update && apt-get upgrade

步骤 2:安装 Certbot 客户端

Certbot 是一个免费、开源的 ACME 客户端,用于自动获取、安装和续订来自 Let’s Encrypt 的 SSL/TLS 证书,使您的服务器轻松启用 HTTPS。

运行以下命令以添加 Certbot 软件源:

sudo add-apt-repository ppa:certbot/certbot

确认安装后,更新软件包列表并为 Apache 安装 Certbot:

apt-get update
apt-get install python-certbot-apache

此时,Certbot 已成功安装,您可以准备获取免费的 Let’s Encrypt SSL 证书。

步骤 3:获取 Let’s Encrypt 证书

可以使用不同的 Certbot 插件来安装 Let's Encrypt 证书。在本指南中,我们将使用 Nginx 插件,该插件会自动处理配置更新并重新加载 Nginx。

运行以下命令并将“domain.com”替换为您的实际域名。

certbot --apache -d domain.com -d www.domain.com

首次生成证书时,系统会要求您输入电子邮件地址并同意 Certbot 的服务条款。

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

如果您希望所有网站访问者都重定向到 HTTP(这是推荐的选项),请选择数字 2 并按“Enter”键。

如果 Let's Encrypt SSL 证书安装成功,您将获得以下输出。

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at
/etc/letsencrypt/live/domain.com/fullchain.pem. Your cert will
expire on 2017-10-23. To obtain a new or tweaked version of this
certificate in the future, simply run certbot again with the
"certonly" option. 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

步骤 4:验证 SSL 安装

现在,您应该已经在“domain.com”域名上成功安装并配置了 Let's Encrypt SSL 证书。您可以访问https://domain.com进行检查。

Let's Encrypt SSL 证书的有效期为 90 天,我们将通过创建 cron 任务来配置证书自动续订。Let's Encrypt 建议每天运行两次自动续订 cron 任务。因此,请编辑 crontab 文件。

crontab -e

在文件中添加以下行:

* */12 * * * /usr/bin/certbot renew >/dev/null 2>&1