在CentOS上配置Nginx以使用SSL證書涉及幾個步驟。以下是一個基本的指南,幫助你完成這個過程:
如果你還沒有安裝Nginx,可以使用以下命令進行安裝:
sudo yum install epel-release
sudo yum install nginx
你可以從Let’s Encrypt免費獲取SSL證書,或者購買一個商業證書。以下是使用Let’s Encrypt的步驟:
Certbot是一個自動化的工具,可以幫助你獲取和續訂Let’s Encrypt證書。首先,安裝Certbot和Nginx插件:
sudo yum install certbot python2-certbot-nginx
然后,運行Certbot來獲取證書:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成證書的獲取過程。Certbot會自動修改Nginx配置文件以啟用SSL。
如果你手動配置Nginx,可以編輯Nginx配置文件(通常位于/etc/nginx/nginx.conf或/etc/nginx/conf.d/default.conf),添加或修改以下內容:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
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 systemctl restart nginx
確保Nginx正確配置并運行SSL證書:
sudo nginx -t
如果沒有錯誤,你應該會看到類似以下的輸出:
nginx: configuration file /etc/nginx/nginx.conf test is successful
Let’s Encrypt證書通常每90天過期一次。Certbot可以自動續訂證書。你可以設置一個cron任務來定期檢查并續訂證書:
sudo crontab -e
添加以下行:
0 0,12 * * * certbot renew --post-hook "systemctl reload nginx"
這會每天檢查證書是否需要續訂,并在續訂后重新加載Nginx。
通過以上步驟,你應該能夠在CentOS上成功配置Nginx以使用SSL證書。