在Nginx中设置SSL证书可以让你启用HTTPS,从而提高网站的安全性。以下是一个基本的步骤指南,帮助你在Nginx中设置SSL证书:
1. 获取SSL证书
你可以从多个来源获取SSL证书,包括:
- Let’s Encrypt(免费)
- 商业CA(付费)
使用Let’s Encrypt获取证书
-
安装Certbot和Nginx插件:
sudo apt update sudo apt install certbot python3-certbot-nginx -
运行Certbot来获取并安装证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com按照提示完成验证过程。
2. 配置Nginx
Certbot会自动修改你的Nginx配置文件以启用HTTPS。你可以在/etc/nginx/sites-available/目录下找到生成的配置文件,通常命名为yourdomain.com-le-ssl.conf。
示例配置
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
root /var/www/html;
index index.html index.htm;
location ~ /\.ht {
deny all;
}
location / {
try_files $uri $uri/ =404;
}
}
3. 测试配置并重启Nginx
在应用新的配置之前,先测试Nginx配置是否正确:
sudo nginx -t
如果没有错误,重启Nginx以应用新的配置:
sudo systemctl restart nginx
4. 验证SSL证书
打开浏览器并访问https://yourdomain.com,你应该能看到一个安全的连接,并且浏览器地址栏会显示一个锁形图标。
5. 自动续期
Let’s Encrypt证书通常每90天过期一次。Certbot会自动处理续期过程,但你需要确保cron任务或systemd服务正在运行。
检查Certbot自动续期状态
sudo certbot renew --dry-run
如果有任何问题,Certbot会发送通知。
通过以上步骤,你应该能够在Nginx中成功设置SSL证书并启用HTTPS。
以上就是关于“如何在nginx中设置SSL证书”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm