amazon lightsail搭建LAMP_PHP_8站点,定时刷新lets encrypt免费证书
证书更新脚本
这个脚本会自动检查certbot是否存在,如果不存在则尝试安装,并执行证书更新。
sudo vi /opt/bitnami/scripts/letsencrypt/renew.sh
脚本内容如下:
#!/bin/bash
# 获取certbot实际路径
CERTBOT=$(which certbot)
# 日志设置
LOG_DIR="/var/log/letsencrypt"
LOG_FILE="$LOG_DIR/renew.log"
mkdir -p $LOG_DIR
# 记录开始时间
echo "==============================================" >> $LOG_FILE
echo "$(date) - 开始证书更新流程" >> $LOG_FILE
# 检查certbot是否存在
if [ ! -f "$CERTBOT" ]; then
echo "$(date) - 错误: certbot 未找到! 请检查安装" >> $LOG_FILE
echo "$(date) - 尝试自动安装 certbot..." >> $LOG_FILE
# 尝试自动安装 (Ubuntu/Debian)
if [ -f /etc/debian_version ]; then
apt update &>> $LOG_FILE
apt install -y certbot python3-certbot-apache &>> $LOG_FILE
# CentOS/RHEL
elif [ -f /etc/redhat-release ]; then
yum install -y epel-release &>> $LOG_FILE
yum install -y certbot python3-certbot-apache &>> $LOG_FILE
fi
# 重新检查
CERTBOT=$(which certbot)
if [ ! -f "$CERTBOT" ]; then
echo "$(date) - 自动安装失败! 请手动安装certbot" >> $LOG_FILE
exit 1
else
echo "$(date) - certbot 安装成功: $CERTBOT" >> $LOG_FILE
fi
fi
# 执行证书更新
echo "$(date) - 执行证书更新命令" >> $LOG_FILE
## 注意,由于我们使用的是独立模式,所以需要先停止apache,更新完之后再启动apache
$CERTBOT renew --standalone --noninteractive --pre-hook "/opt/bitnami/scripts/apache/stop.sh" --post-hook "/opt/bitnami/scripts/apache/start.sh" >> $LOG_FILE 2>&1
# 检查结果
if [ $? -eq 0 ]; then
echo "$(date) - ✅ 证书更新成功" >> $LOG_FILE
else
echo "$(date) - ❌ 证书更新失败! 请检查日志" >> $LOG_FILE
fi
# 添加空行分隔日志条目
echo "" >> $LOG_FILE
初始化证书
由于我们使用的环境已经安装好apache,而且apache并不是通过systemctl管理的,所以我们需要使用certbot的standalone模式来申请证书。
// 需要替换下面命令的sub.yourdomain.com(支持二级域名), example@yourdomain.com
sudo certbot certonly --standalone -d sub.yourdomain.com --email example@yourdomain.com --agree-tos --noninteractive
此时,证书是下载到/etc/letsencrypt/live目录下的。
配置apache的vhost
打开
vim /opt/bitnami/apache/conf/extra/httpd-vhosts.conf
参考配置
<VirtualHost *:80>
#ServerAdmin noreply@mail.petin.life
DocumentRoot "/data/wwwroot/xxx"
ServerName sub.yourdomain.com
ErrorLog "logs/sub.yourdomain.com-error_log"
CustomLog "logs/sub.yourdomain.com-access_log" common
<Directory "/data/wwwroot/xxx">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:443>
#ServerAdmin noreply@mail.petin.life
DocumentRoot "/data/wwwroot/xxx"
ServerName sub.yourdomain.com
ErrorLog "logs/sub.yourdomain.com-error_log"
CustomLog "logs/sub.yourdomain.com-access_log" common
<Directory "/data/wwwroot/xxx">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/sub.yourdomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/sub.yourdomain.com/privkey.pem
</VirtualHost>
设置定时任务
sudo crontab -e
添加以下(每周日凌晨3点运行)
# 每周日凌晨3点执行证书更新脚本
0 3 * * 0 /opt/bitnami/scripts/letsencrypt/renew.sh

浙公网安备 33010602011771号