温馨提示×

ubuntu apache2怎么配置https

小樊
43
2026-09-17 08:10:41
栏目: 智能运维

在 Ubuntu 上用 Apache2 配置 HTTPS,通常有两种常见方式:

  1. 使用 Let’s Encrypt(推荐,免费、自动续期)
  2. 使用自签名证书(测试用)

下面分别说明。


一、使用 Let’s Encrypt 配置 HTTPS(推荐)

1. 安装 Apache 和 Certbot

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

2. 确保域名解析正确

  • 你的域名(如 example.com)必须 A 记录指向服务器 IP
  • 确保 80 端口可访问

3. 获取并自动配置 HTTPS

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

按提示选择:

  • 是否重定向 HTTP → HTTPS(建议选 2)

4. 验证自动续期

sudo certbot renew --dry-run

✅ 成功标志:

  • 访问 https://example.com 显示锁标志
  • 证书自动续期

二、使用自签名证书(仅测试)

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. 创建 Apache HTTPS 配置

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

内容示例:

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

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

3. 启用模块和站点

sudo a2enmod ssl
sudo a2ensite ssl.conf
sudo systemctl restart apache2

三、防火墙(如有)

sudo ufw allow 80
sudo ufw allow 443

四、常见问题

❌ 浏览器提示“不安全”

  • 自签名证书正常现象
  • Let’s Encrypt 则检查域名解析和 80 端口

❌ Apache 无法启动

sudo apache2ctl configtest

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

  • 是 云服务器还是本地
  • 域名情况
  • 是否只是本地测试

我可以给你更精确的配置。

0 踩