在Ubuntu下为Apache2安装SSL证书,主要有两种方式:使用Let’s Encrypt免费证书和手动安装证书,以下是具体步骤:
安装Apache2和SSL模块
sudo apt update
sudo apt install apache2 libapache2-mod-ssl
sudo a2enmod ssl # 启用SSL模块
获取Let’s Encrypt证书
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com # 替换为你的域名
按提示完成操作,Certbot会自动配置Apache并安装证书。
验证配置
sudo systemctl restart apache2
https://yourdomain.com
,查看是否显示锁图标。设置自动续期(可选)
Let’s Encrypt证书有效期90天,可通过Cron任务自动续期:
sudo crontab -e
添加以下内容:
0 0,12 * * * certbot renew --post-hook "systemctl reload apache2"
准备证书文件
确保拥有.crt
(证书)、.key
(私钥)和.chain
(证书链)文件,上传至服务器/etc/apache2/ssl/
目录(需提前创建该目录)。
配置Apache
编辑SSL配置文件(如/etc/apache2/sites-available/default-ssl.conf
):
sudo nano /etc/apache2/sites-available/default-ssl.conf
替换以下内容为你的证书路径:
SSLCertificateFile /etc/apache2/ssl/yourdomain.crt
SSLCertificateKeyFile /etc/apache2/ssl/yourdomain.key
SSLCertificateChainFile /etc/apache2/ssl/yourdomain.chain # 如有证书链
启用站点并重启服务
sudo a2ensite default-ssl.conf # 启用SSL站点配置
sudo systemctl restart apache2
验证配置
浏览器访问https://yourdomain.com
,确认HTTPS连接正常。
编辑/etc/apache2/sites-available/000-default.conf
,在<VirtualHost *:80>
中添加:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
重启Apache生效。
600
,确保安全:sudo chmod 600 /etc/apache2/ssl/*.key
。以上步骤参考自。