要配置Apache2以支持HTTPS,您需要执行以下步骤:
1. 获取SSL证书
首先,您需要一个SSL证书。您可以从以下途径获取:
- Let’s Encrypt(免费)
- 商业CA(付费)
使用Let’s Encrypt获取证书
-
安装Certbot:
sudo apt update sudo apt install certbot python3-certbot-apache
-
运行Certbot以获取并安装证书:
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
按照提示完成操作。
2. 配置Apache2
Certbot会自动为您生成SSL配置文件并启用HTTPS。如果您需要手动配置,可以按照以下步骤进行:
-
打开Apache2的主配置文件:
sudo nano /etc/apache2/apache2.conf
-
确保以下模块已启用:
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so Include /etc/apache2/sites-available/*.conf
-
创建或编辑SSL站点配置文件:
sudo nano /etc/apache2/sites-available/yourdomain.com-le-ssl.conf
-
添加以下内容:
ServerAdmin webmaster@yourdomain.com DocumentRoot /var/www/html ServerName yourdomain.com ServerAlias www.yourdomain.com SSLEngine on SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined -
启用SSL站点:
sudo a2ensite yourdomain.com-le-ssl.conf
-
禁用HTTP站点(可选):
sudo a2dissite 000-default.conf
-
重新加载Apache2配置:
sudo systemctl reload apache2
3. 验证配置
打开浏览器并访问https://yourdomain.com
,您应该能够看到您的网站,并且浏览器地址栏会显示安全锁图标。
4. 自动续期证书
Let’s Encrypt证书每90天需要续期一次。Certbot会自动处理续期,但您也可以手动运行以下命令来测试续期:
sudo certbot renew --dry-run
如果一切正常,Certbot会在证书到期前30天自动续期。
通过以上步骤,您应该能够成功配置Apache2以支持HTTPS。