在CentOS上安装Nginx并配置SSL证书,可以按照以下步骤进行:
首先,确保你的系统已经更新到最新状态:
sudo yum update -y
然后,安装EPEL仓库(如果尚未安装):
sudo yum install epel-release -y
接下来,安装Nginx:
sudo yum install nginx -y
启动Nginx服务并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
你可以从Let’s Encrypt免费获取SSL证书。使用Certbot工具来简化这个过程。
首先,安装Certbot和Nginx插件:
sudo yum install certbot python3-certbot-nginx -y
然后,运行Certbot来获取并安装SSL证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
将yourdomain.com替换为你的实际域名。
Certbot会自动配置Nginx以使用SSL,并创建一个临时文件来测试配置。如果一切正常,它会提示你重载Nginx服务。
打开浏览器,访问https://yourdomain.com,你应该能看到一个安全的连接(锁形图标)。
Let’s Encrypt的证书有效期为90天。Certbot会自动为你设置一个cron任务或systemd定时器来续期证书。
你可以手动测试续期过程:
sudo certbot renew --dry-run
如果没有错误,证书应该已经成功续期。
确保你的防火墙允许HTTPS流量:
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
为了提高安全性,你可以启用HTTP Strict Transport Security (HSTS)。编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf或/etc/nginx/conf.d/default.conf),添加以下行:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
然后重新加载Nginx:
sudo systemctl reload nginx
完成以上步骤后,你的CentOS服务器上应该已经成功安装并配置了Nginx和SSL证书。