VPS 安裝 Nginx 與 PHP 教學:打造 LEMP 高效網頁伺服器

VPSNginxPHPLEMPWeb Server教學安裝網站伺服器LNMP性能優化

本文以 Ubuntu 24.04 為例,說明如何安裝 LEMP(Linux + Nginx + MySQL + PHP)環境,讓您的 VPS 成為一台完整的 Web Server。

安裝 Nginx

  1. 更新套件清單並安裝 Nginx:
    apt update
    apt install nginx -y
  2. 啟動並設定開機自動啟動:
    systemctl start nginx
    systemctl enable nginx
  3. 開放防火牆:
    ufw allow 80/tcp
    ufw allow 443/tcp
  4. 在瀏覽器輸入您的 VPS IP,看到 Nginx 歡迎頁面即表示安裝成功。

安裝 PHP 8.3

  1. 安裝 PHP-FPM 及常用擴充模組:
    apt install php8.3-fpm php8.3-mysql php8.3-curl php8.3-mbstring \
      php8.3-xml php8.3-zip php8.3-gd php8.3-intl -y
  2. 確認 PHP 版本:
    php -v
  3. 確認 PHP-FPM 正在運行:
    systemctl status php8.3-fpm

安裝 MySQL

  1. 安裝 MySQL Server:
    apt install mysql-server -y

    若偏好 MariaDB,可改用:

    apt install mariadb-server -y
  2. 執行安全性設定精靈:
    mysql_secure_installation

    建議設定 root 密碼、移除匿名帳號、禁止遠端 root 登入、刪除測試資料庫。

設定 Nginx 虛擬主機

  1. 建立網站目錄:
    mkdir -p /var/www/example.com
    chown -R www-data:www-data /var/www/example.com
  2. 建立 Nginx 設定檔:
    nano /etc/nginx/sites-available/example.com

    寫入以下內容(請將 example.com 替換為您的網域):

    server {
        listen 80;
        server_name example.com www.example.com;
        root /var/www/example.com;
        index index.php index.html;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        }
    
        location ~ /\.ht {
            deny all;
        }
    }
  3. 啟用網站並測試設定:
    ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    nginx -t
    systemctl reload nginx

測試 PHP 是否正常運作

  1. 建立測試檔案:
    echo "<?php phpinfo();" > /var/www/example.com/info.php
  2. 在瀏覽器開啟 http://您的VPS_IP/info.php,看到 PHP 資訊頁面表示設定成功。
  3. 測試完成後請立即刪除此檔案(避免洩漏伺服器資訊):
    rm /var/www/example.com/info.php

安裝 SSL 憑證(Let's Encrypt)

使用 Certbot 取得免費 SSL 憑證:

apt install certbot python3-certbot-nginx -y
certbot --nginx -d example.com -d www.example.com

Certbot 會自動修改 Nginx 設定並啟用 HTTPS。憑證每 90 天自動續約,可用以下指令測試續約:

certbot renew --dry-run

需要主機來實作?

侃瑞科技提供 cPanel 虛擬主機與 VPS,教學裡的操作開箱即用。

查看方案 →
LINE 諮詢