溫馨提示×

LNMP在Ubuntu上如何配置SSL

小樊
46
2025-09-06 12:55:10
欄目: 云計算

在Ubuntu上配置LNMP(Linux, Nginx, MySQL, PHP)以使用SSL涉及幾個步驟。以下是一個基本的指南,幫助你設置SSL證書并配置Nginx以使用HTTPS。

1. 安裝Certbot

Certbot是一個自動化的工具,用于獲取和續訂Let’s Encrypt的SSL證書。你可以使用以下命令安裝Certbot:

sudo apt update
sudo apt install certbot python3-certbot-nginx

2. 獲取SSL證書

使用Certbot獲取SSL證書。運行以下命令并按照提示操作:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

yourdomain.comwww.yourdomain.com替換為你的實際域名。Certbot會自動配置Nginx并重啟服務。

3. 驗證配置

Certbot會自動驗證你的域名所有權,并配置Nginx以使用HTTPS。你可以通過訪問https://yourdomain.com來驗證配置是否成功。

4. 自動續訂證書

Let’s Encrypt的證書有效期為90天。Certbot會自動設置一個cron作業來定期檢查并續訂證書。你可以手動測試續訂過程:

sudo certbot renew --dry-run

如果沒有錯誤,證書將成功續訂。

5. 配置Nginx(可選)

如果你需要進一步自定義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

6. 配置防火墻

確保你的防火墻允許HTTP(80)和HTTPS(443)流量。如果你使用的是UFW(Uncomplicated Firewall),可以運行以下命令:

sudo ufw allow 'Nginx Full'

完成以上步驟后,你的LNMP環境應該已經成功配置了SSL。

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