确保服务器已安装Nginx且正常运行,域名已解析到服务器IP地址。
sudo systemctl status nginx(若未安装,运行sudo apt update && sudo apt install nginx安装)。Certbot是Let’s Encrypt的官方客户端,可自动获取和配置SSL证书。
运行以下命令安装Certbot及Nginx插件:
sudo apt update && sudo apt install certbot python3-certbot-nginx
使用Certbot为域名生成免费证书,命令会自动处理证书申请、验证及Nginx配置更新。
sudo certbot --nginx -d your_domain.com -d www.your_domain.com
-d参数指定域名(可同时添加主域名和子域名,如www)。Certbot会自动修改Nginx配置文件(通常位于/etc/nginx/sites-available/或/etc/nginx/conf.d/),添加HTTPS监听端口(443)及证书路径。
sudo nginx -t(若输出“syntax is ok”,说明配置正确)。sudo systemctl reload nginx(使配置生效)。在浏览器中访问https://your_domain.com,若地址栏显示锁图标,则表示SSL证书配置成功。
Let’s Encrypt证书有效期为90天,Certbot默认会添加定时任务(每天检查),但需手动测试续期功能。
运行以下命令模拟续期:sudo certbot renew --dry-run(若无报错,说明续期功能正常)。
若已通过其他途径(如购买商业证书)获得证书文件,可按以下步骤手动配置:
.crt)、私钥(.key)及中间证书(若有,.ca-bundle)上传至服务器,建议存放在/etc/nginx/ssl/目录(需手动创建)。sudo mkdir -p /etc/nginx/ssl/
sudo cp your_domain.crt /etc/nginx/ssl/
sudo cp your_domain.key /etc/nginx/ssl/
sudo cp your_domain.ca-bundle /etc/nginx/ssl/ # 可选,中间证书
server块及强制HTTP跳转规则:# 强制HTTP跳转到HTTPS
server {
listen 80;
server_name your_domain.com www.your_domain.com;
return 301 https://$host$request_uri;
}
# HTTPS配置
server {
listen 443 ssl;
server_name your_domain.com www.your_domain.com;
# 证书路径
ssl_certificate /etc/nginx/ssl/your_domain.crt;
ssl_certificate_key /etc/nginx/ssl/your_domain.key;
ssl_trusted_certificate /etc/nginx/ssl/your_domain.ca-bundle; # 可选
# SSL安全配置(推荐)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# 网站根目录
root /var/www/your_domain;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
sudo nginx -t && sudo systemctl reload nginx通过以上步骤,即可在Ubuntu服务器上为Nginx配置SSL证书,实现网站HTTPS加密访问。