在Nginx中设置SSL证书可以让你启用HTTPS,从而提高网站的安全性。以下是一个基本的步骤指南,帮助你在Nginx中设置SSL证书:
你可以从多个来源获取SSL证书,包括:
安装Certbot和Nginx插件:
sudo apt update
sudo apt install certbot python3-certbot-nginx
运行Certbot来获取并安装证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成验证过程。
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;
}
}
在应用新的配置之前,先测试Nginx配置是否正确:
sudo nginx -t
如果没有错误,重启Nginx以应用新的配置:
sudo systemctl restart nginx
打开浏览器并访问https://yourdomain.com,你应该能看到一个安全的连接,并且浏览器地址栏会显示一个锁形图标。
Let’s Encrypt证书通常每90天过期一次。Certbot会自动处理续期过程,但你需要确保cron任务或systemd服务正在运行。
sudo certbot renew --dry-run
如果有任何问题,Certbot会发送通知。
通过以上步骤,你应该能够在Nginx中成功设置SSL证书并启用HTTPS。