溫馨提示×

centos nginx SSL證書配置

小樊
115
2025-02-13 09:24:50
欄目: 云計算

在CentOS上配置Nginx以使用SSL證書涉及幾個步驟。以下是一個基本的指南,幫助你完成這個過程:

1. 安裝Nginx

如果你還沒有安裝Nginx,可以使用以下命令進行安裝:

sudo yum install epel-release
sudo yum install nginx

2. 獲取SSL證書

你可以從Let’s Encrypt免費獲取SSL證書,或者購買一個商業證書。以下是使用Let’s Encrypt的步驟:

使用Certbot獲取證書

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。

3. 配置Nginx

如果你手動配置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;
    }
}

4. 重啟Nginx

保存配置文件后,重啟Nginx以應用更改:

sudo systemctl restart nginx

5. 測試配置

確保Nginx正確配置并運行SSL證書:

sudo nginx -t

如果沒有錯誤,你應該會看到類似以下的輸出:

nginx: configuration file /etc/nginx/nginx.conf test is successful

6. 自動續訂證書

Let’s Encrypt證書通常每90天過期一次。Certbot可以自動續訂證書。你可以設置一個cron任務來定期檢查并續訂證書:

sudo crontab -e

添加以下行:

0 0,12 * * * certbot renew --post-hook "systemctl reload nginx"

這會每天檢查證書是否需要續訂,并在續訂后重新加載Nginx。

通過以上步驟,你應該能夠在CentOS上成功配置Nginx以使用SSL證書。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女