在Ubuntu上配置LNMP(Linux, Nginx, MySQL, PHP)以使用SSL涉及幾個步驟。以下是一個基本的指南,幫助你設置SSL證書并配置Nginx以使用HTTPS。
Certbot是一個自動化的工具,用于獲取和續訂Let’s Encrypt的SSL證書。你可以使用以下命令安裝Certbot:
sudo apt update
sudo apt install certbot python3-certbot-nginx
使用Certbot獲取SSL證書。運行以下命令并按照提示操作:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
將yourdomain.com
和www.yourdomain.com
替換為你的實際域名。Certbot會自動配置Nginx并重啟服務。
Certbot會自動驗證你的域名所有權,并配置Nginx以使用HTTPS。你可以通過訪問https://yourdomain.com
來驗證配置是否成功。
Let’s Encrypt的證書有效期為90天。Certbot會自動設置一個cron作業來定期檢查并續訂證書。你可以手動測試續訂過程:
sudo certbot renew --dry-run
如果沒有錯誤,證書將成功續訂。
如果你需要進一步自定義Nginx配置,可以編輯Nginx配置文件。通常,Certbot會在/etc/nginx/sites-available/
目錄下創建一個符號鏈接到/etc/nginx/sites-enabled/
目錄。
例如,編輯你的站點配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
確保配置文件包含以下內容:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
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.php index.html index.htm;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根據你的PHP版本調整
}
location / {
try_files $uri $uri/ =404;
}
}
保存并退出編輯器,然后測試Nginx配置:
sudo nginx -t
如果沒有錯誤,重啟Nginx服務:
sudo systemctl restart nginx
確保你的防火墻允許HTTP(80)和HTTPS(443)流量。如果你使用的是UFW(Uncomplicated Firewall),可以運行以下命令:
sudo ufw allow 'Nginx Full'
完成以上步驟后,你的LNMP環境應該已經成功配置了SSL。