在 Ubuntu 上通过 Apache 开启 HTTPS,通常分为 安装 Apache → 获取 SSL 证书 → 配置虚拟主机 → 强制跳转(可选) 几步。下面以 Ubuntu 20.04/22.04 为例说明。
sudo apt update
sudo apt install apache2 -y
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com
替换
example.com为你自己的域名
certbot 会自动:
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/ssl/private/apache-selfsigned.key \
-out /etc/ssl/certs/apache-selfsigned.crt
sudo a2enmod ssl
sudo systemctl restart apache2
sudo nano /etc/apache2/sites-available/example.com.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
<Directory /var/www/html>
AllowOverride All
</Directory>
</VirtualHost>
启用站点:
sudo a2ensite example.com.conf
sudo systemctl reload apache2
编辑 80 端口配置:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
或在使用 certbot 时选择:
2: Redirect - Make all requests redirect to secure HTTPS access
sudo ufw allow 'Apache Full'
浏览器访问:
https://example.com
sudo certbot renew --dry-run
如果你愿意,可以告诉我:
我可以给你更精确的配置示例。