在Ubuntu上为Nginx安装SSL证书的步骤如下:
首先,确保你的Ubuntu系统上已经安装了Nginx。如果尚未安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install nginx
安装完成后,可以通过以下命令验证Nginx是否正常运行:
sudo systemctl start nginx
sudo systemctl enable nginx
你可以选择购买商业SSL证书,或者使用Let’s Encrypt提供的免费SSL证书。以下是使用Let’s Encrypt获取证书的步骤:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
将yourdomain.com
替换为你的域名。根据提示完成配置,Certbot会自动为你配置Nginx。
编辑Nginx配置文件:找到并打开你的Nginx配置文件,通常位于/etc/nginx/sites-available/default
或/etc/nginx/nginx.conf
。
添加SSL配置:在server
块中添加以下内容:
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;
location / {
proxy_pass http://localhost:3000; # 根据需要调整
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
将yourdomain.com
替换为你的域名。
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
在重启Nginx之前,先测试配置是否有效:
sudo nginx -t
如果一切正常,重启Nginx使更改生效:
sudo systemctl restart nginx
如果你使用的是Let’s Encrypt免费证书,可以使用Certbot工具来自动续订证书。首先安装Certbot:
sudo apt install certbot python3-certbot-nginx
然后运行Certbot来自动配置和续订证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Certbot会自动更新Nginx配置并设置自动续订任务。
通过以上步骤,你应该能够在Ubuntu上成功安装和配置Nginx以使用SSL证书。现在,你的网站应该可以通过HTTPS安全访问了。