温馨提示×

ubuntu apache2如何ssl

小樊
47
2026-09-11 04:37:40
栏目: 云计算

在 Ubuntu 上使用 Apache2 配置 SSL(HTTPS) 通常有两种常见方式:


一、使用 Let’s Encrypt 免费证书(推荐,适合公网域名)

1. 安装 certbot

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

2. 申请并自动配置 SSL

sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

替换 yourdomain.com 为你的真实域名
需要确保域名已解析到服务器 IP

3. 自动续期测试

sudo certbot renew --dry-run

certbot 会自动:

  • 生成证书
  • 配置 Apache 虚拟主机
  • 开启 80 → 443 跳转

二、使用自签名证书(适合测试 / 内网)

1. 生成私钥和证书

sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout /etc/ssl/private/apache-selfsigned.key \
  -out /etc/ssl/certs/apache-selfsigned.crt

按提示填写信息(Common Name 可填 IP 或域名)


2. 启用 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

3. 配置虚拟主机

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

示例内容:

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

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
    SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

    <Directory /var/www/html>
        AllowOverride All
    </Directory>
</VirtualHost>

启用站点:

sudo a2ensite ssl.conf
sudo systemctl restart apache2

三、强制 HTTP 跳转到 HTTPS(可选)

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

四、防火墙放行

sudo ufw allow 80
sudo ufw allow 443

常见问题

  • 证书不受信任:自签名证书浏览器会警告,属正常
  • Apache 无法启动:检查端口冲突或证书路径
  • 域名访问不了:确认 DNS + 防火墙

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

  • 公网域名 还是 内网/IP
  • Ubuntu 版本(20.04 / 22.04 / 24.04)

我可以给你更精确的步骤。

0