系统性能优化centosnginx

centos nginx申请免费https证书

2022-04-15  本文已影响0人  至爱雅鸿_e631

前言

各大厂有免费证书申请渠道,但是需要配置DNS,某些情况下无法掌控域名的DNS解析,Let's Encrypt可以很好的解决这个问题,只要你有网站的管理权就能搞定,不过证书的有效期是三个月,需要搞一个定时任务隔一段时间申请一次。

操作步骤

1.安装certbot

##安装前置依赖
yum install -y epel-release
yum install python2-certbot-nginx
##安装certbot
yum install -y certbot

2.配置nginx

不管你的nginx是否已投入使用(投入使用的意思是已经在生产环境运行)均需要配置以下内容

### 如果已经配置了root,请使用alias,不过alias与root的解析方式有差别,注意文件夹的层级
location ^~/.well-known/acme-challenge/{
        default_type "text/plain";
        root /opt/ylbzj/nginx/html;
}

如果你的nginx是负载状态,你只需要在其中一台机器上安装certbot,另一台机器配置转发就行,假设你安装certbot的机器ip为10.10.0.1,另一台机器的nginx配置为

location ^~/.well-known/acme-challenge/{
        proxy_pass http://10.10.0.1/.well-known/acme-challenge/;
}

3.生成key

## --nginx表示生成nginx的key
## -w指的是根目录,即root指向的目录
## -d是域名
## -m是邮箱
certbot certonly --nginx -w /opt/nginx/html -d yhwch.com -m zhiaiyahong@yhwch.com

4.定时任务生成key

单机的nginx使用下面这个脚本就够用了,使用方式是:先手动生成一次证书,然后手动执行sh certbotCron.sh(假设你将脚本命名为这个,并且存储在根目录下),会自动将定时任务加到crontab中,并且不会影响现有的crontab任务,后面等着定时任务自己执行就行,有条件的最好加个通知。


#!/bin/bash
echo $(date +"%Y-%m-%d %H:%M:%S")"证书刷新开始执行======================="
result=$(certbot renew)
#result="- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Processing /etc/letsencrypt/renewal/ylbzj.hebei.gov.cn.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - The following certificates are not due for renewal yet: /etc/letsencrypt/live/ylbzj.hebei.gov.cn/fullchain.pem expires on 2022-07-10 (skipped) No renewals were attempted. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
echo "------------重置证书周期结果为---------"
echo $result
echo "-----------结果数据结束------------"
renewisok=$(echo ${result#*are})
renewisok2=$(echo ${renewisok%yet*})
echo "------------字符分割结果为----------"
echo $renewisok2
echo "------------分割结束------------"

if [ "${renewisok2}" = "not due for renewal" ];then
data1=$(echo ${renewisok#*on})
data2=$(echo ${data1%(skipped*})
echo "还没到期,不能更新,到期日期为"$data2
crondata=$(date -d "$data2 -25 day" +%Y-%m-%d)
echo "crontab 执行日期为"$crondata
yue=$(date -d "$crondata" +%m)
ri=$(date -d "$crondata" +%d)
cronstr=$(echo "0 0 "$ri" "$yue"* sh /root/certbotCron.sh >> ~/log_certbot_"$crondata".log")
echo $cronstr > ~/cronconf
$(sed -i 's/*/ */g' ~/cronconf)
$(crontab -l |grep -v $crondata >> ~/cronconf)
$(crontab ~/cronconf)
echo "crontab 任务列表如下:"
crontab -l
else
echo "到期了,已经更新,开始拷贝文件至2号服务器,假设机器为10.10.0.2并且做好了免密登录"
suffix=$(date +"%Y%m%d")
zipfilename="letsencrypt_"$suffix".tar.gz"
echo "压缩文件名称为:"$zipfilename
cd /etc
zipcommand=$(tar -czvf $zipfilename letsencrypt)
kaobei=$(scp -r $zipfilename root@10.10.0.2:/etc)
ssh root@172.20.191.55 "cd /etc;tar -zxvf $zipfilename -C /etc"
echo "2号服务器文件拷贝完成,再次执行脚本填充下一个周期的定时任务"
sh ~/certbotCron.sh
fi
echo $(date +"%Y-%m-%d %H:%M:%S")"证书刷新执行结束======================="
上一篇下一篇

猜你喜欢

热点阅读