温馨提示×

ubuntu apache2怎么配置SSL证书

小樊
42
2026-08-16 20:20:25
栏目: 云计算

在 Ubuntu 上给 Apache2 配置 SSL 证书,常见有两种情况:
使用 Let’s Encrypt(免费、自动续签,推荐)
使用自己购买的 SSL 证书(或自签名)

下面分别说明。


一、使用 Let’s Encrypt(最推荐)

1️⃣ 安装 Certbot

sudo apt update
sudo apt install certbot python3-certbot-apache -y

2️⃣ 申请并自动配置 SSL

sudo certbot --apache

按提示操作:

  • 输入你的 域名(如 example.com
  • 选择是否 强制 HTTPS(建议选 2

✅ Certbot 会自动:

  • 申请证书
  • 配置 Apache SSL
  • 设置 80 → 443 跳转

3️⃣ 验证 Apache 配置

sudo apache2ctl configtest
sudo systemctl reload apache2

4️⃣ 自动续签(默认已配置)

sudo certbot renew --dry-run

Let’s Encrypt 证书 90 天有效期,Ubuntu 会自动通过 systemd timer 续签。


二、使用已有 SSL 证书(购买 / 自签)

1️⃣ 启用 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

2️⃣ 准备证书文件

假设证书文件如下:

/etc/ssl/certs/example.com.crt
/etc/ssl/private/example.com.key
/etc/ssl/certs/example.com.ca-bundle   # 可选

⚠️ private key 权限必须安全

sudo chmod 600 /etc/ssl/private/example.com.key

3️⃣ 创建 Apache SSL 虚拟主机

新建配置文件:

sudo nano /etc/apache2/sites-available/example-ssl.conf

示例配置:

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.com.crt
    SSLCertificateKeyFile /etc/ssl/private/example.com.key
    SSLCertificateChainFile /etc/ssl/certs/example.com.ca-bundle

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

4️⃣ 启用站点并重启

sudo a2ensite example-ssl.conf
sudo systemctl reload apache2

三、HTTP 自动跳转 HTTPS(强烈建议)

编辑 HTTP 站点配置:

sudo nano /etc/apache2/sites-available/000-default.conf

添加:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

重启:

sudo systemctl reload apache2

四、常见问题排查

❌ Apache 无法启动

sudo journalctl -xe
sudo apache2ctl -S

❌ HTTPS 访问不了

  • 检查 443 端口是否开放
  • 云服务器需放行 安全组 / 防火墙
sudo ufw allow 443/tcp

五、快速总结

场景 推荐方式
公网网站 ✅ Let’s Encrypt
内网 / 测试 自签 SSL
企业证书 上传 CRT + KEY

如果你愿意,可以告诉我:

  • ✅ Ubuntu 版本(20.04 / 22.04 / 24.04)
  • ✅ 是否有 域名
  • ✅ 是 云服务器还是本地

我可以给你 完全针对你环境的配置命令

0