首页 > 计算机技术 > Web服务器 > Nginx

ubuntu20.04配置nginx https及自动续期

原创 lihf8515 2025年01月16日 14:50
来源:本站 阅读:609

ubuntu20.04配置nginx https

在Ubuntu 20.04上配置Nginx以使用HTTPS,你需要执行以下步骤:

一、安装Nginx:

sudo apt update
sudo apt install nginx

二、使用以下命令生成SSL证书,替换your_domain.com为你的域名。根据提示输入你的电子邮箱地址,按A和Y键继续,最后会提示生成成功。

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com -d www.your_domain.com

三、Certbot会自动为你的Nginx服务器配置SSL证书,如果你的nginx配置文件不是系统默认的路径,则可能自动配置失败,需要手动修改配置。

确认Nginx配置文件没有错误,并重启Nginx服务:

sudo nginx -t
sudo systemctl reload nginx

四、现在你的Nginx服务器应该通过HTTPS提供服务了。如果你想要手动配置HTTPS,可以编辑Nginx的配置文件(通常位于/etc/nginx/sites-available/default),添加以下内容:

server {
  listen 80;
  server_name your_domain.com;
  return 301 https://$server_name$request_uri;
}
server {
  listen 443 ssl;
  server_name your_domain.com www.your_domain.com;
  ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
  # 其他配置...
}

确保替换your_domain.com为你的域名,并指定正确的证书文件路径。然后重新加载Nginx配置:

sudo systemctl reload nginx

五、自动续期

Let's Encrypt提供的证书只有90天的有效期,所以我们要在证书到期之前重新获取,以保证网站正常使用,Certbot提供了一个方便的命令 certbot renew,我们在使用前可以使用以下命令测试是否可用:

certbot renew --dry-run

返回正常的测试结果后,在系统中使用cron创建任务来实现定期更新。

sudo nano /etc/crontab

写入以下内容,意思是每隔两个月的凌晨1时执行更新操作

00 1 * */2 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"

当然,我建议更直观的写入以下内容,执行更新操作。

# 2月
00 0 1 2 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"
# 4月
00 0 1 4 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"
# 6月
00 0 1 6 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"
# 8月
00 0 1 8 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"
# 10月
00 0 1 10 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"
# 12月
00 0 1 12 * certbot renew --quiet --renew-hook "nginx -t && nginx -s reload"

以上步骤成功在Ubuntu 20.04上配置Nginx以使用HTTPS。

友情链接: 海峰收银系统  
Copyright © 2025 hfsoft.top All Rights Reserved.
中华人民共和国工业和信息化部ICP备案序号:皖ICP备2025073039号