PHP 部署教學:CodeIgniter 4 部署到 cPanel 完整指南
雖然雲端平台和容器化部署越來越普及,但傳統的 cPanel 虛擬主機仍然是許多中小企業和個人網站的首選。價格實惠、操作簡單、不需要命令列知識,讓非技術人員也能管理網站。
這篇教學將帶你完整走過 CodeIgniter 4(CI4)部署到 cPanel 虛擬主機的每個步驟,從目錄結構設定、.htaccess 配置、到資料庫連線,讓你的 PHP 專案順利上線。
如果你想了解更完整的部署策略,可以先閱讀 程式部署完整指南。
為什麼選擇 cPanel 虛擬主機
在開始部署之前,先了解 cPanel 虛擬主機的優缺點:
優點
| 優點 | 說明 |
|---|---|
| 價格便宜 | 每月 $3-10 美元即可起步 |
| 操作簡單 | 圖形化介面,不需要命令列 |
| 整合服務 | Email、SSL、資料庫一站搞定 |
| 技術支援 | 主機商提供客服支援 |
| 穩定性 | 成熟技術,問題容易排解 |
缺點
| 缺點 | 說明 |
|---|---|
| 效能限制 | 共享資源,流量大時可能變慢 |
| 彈性較低 | 無法安裝自訂軟體(如 Redis) |
| PHP 版本 | 可能無法使用最新版本 |
| 擴展困難 | 流量增加時需要升級或遷移 |
適用場景
cPanel 虛擬主機適合:
- 企業官網、形象網站
- 中小型電商(搭配 WooCommerce 或自建)
- 部落格、內容網站
- 內部管理系統(低流量)
- 預算有限的 Side Project
CodeIgniter 4 目錄結構

插圖:CodeIgniter 4 目錄結構圖
場景描述:
Technical illustration showing CodeIgniter 4 目錄結構圖. Clean, professional diagram style.
視覺重點:
- Clear presentation of the concept
- Professional technical diagram style
- Easy to understand visual elements
必須出現的元素:
- Relevant technical components
- Clear labels and annotations
- Logical flow or structure
需要顯示的中文字:
無
風格:
Clean flat design, technical illustration, modern infographic style
顏色調性:
Professional blues and grays, with accent colors for emphasis
避免元素:
Cluttered design, realistic photos, complex 3D rendering
在部署之前,必須先了解 CI4 的目錄結構,這對於正確配置非常重要。
標準目錄結構
my-ci4-project/
├── app/ # 應用程式邏輯
│ ├── Config/ # 設定檔
│ ├── Controllers/ # 控制器
│ ├── Models/ # 模型
│ ├── Views/ # 視圖
│ └── ...
├── public/ # 網站根目錄(Web Root)
│ ├── index.php # 入口檔案
│ ├── .htaccess # URL 重寫規則
│ ├── css/
│ ├── js/
│ └── images/
├── writable/ # 快取、日誌、上傳檔案
│ ├── cache/
│ ├── logs/
│ └── uploads/
├── vendor/ # Composer 相依套件
├── .env # 環境設定(敏感資訊)
├── composer.json
└── spark # CLI 工具
重要概念:public 目錄
核心原則:只有 public/ 目錄應該對外公開!
這樣設計的原因:
- app/、writable/、.env 包含敏感資訊
- 如果整個專案都對外公開,攻擊者可能存取設定檔
- public/ 只包含入口檔案和靜態資源
cPanel 部署前準備
1. 確認主機規格
登入 cPanel 後,確認以下資訊:
| 項目 | 建議 | 確認方式 |
|---|---|---|
| PHP 版本 | 8.1+ | cPanel → Select PHP Version |
| MySQL 版本 | 5.7+ 或 8.0 | cPanel → phpMyAdmin |
| 磁碟空間 | 至少 500MB | cPanel → Disk Usage |
| mod_rewrite | 已啟用 | 詢問主機商 |
2. 本地準備工作
在上傳之前,先在本地完成以下步驟:
# 安裝相依套件
composer install --no-dev --optimize-autoloader
# 確認 .env 設定為 production
# CI_ENVIRONMENT = production
3. 壓縮專案
# 排除不需要的檔案
zip -r my-ci4-project.zip . \
-x "*.git*" \
-x "node_modules/*" \
-x ".env" \
-x "writable/cache/*" \
-x "writable/logs/*"
💡 不確定主機規格夠不夠?
PHP 版本、記憶體限制、資料庫配額都會影響網站運作。
預約免費諮詢,讓我們幫你評估主機是否符合需求。
部署方式一:標準部署(推薦)

插圖:cPanel 部署流程圖
場景描述:
Technical illustration showing cPanel 部署流程圖. Clean, professional diagram style.
視覺重點:
- Clear presentation of the concept
- Professional technical diagram style
- Easy to understand visual elements
必須出現的元素:
- Relevant technical components
- Clear labels and annotations
- Logical flow or structure
需要顯示的中文字:
無
風格:
Clean flat design, technical illustration, modern infographic style
顏色調性:
Professional blues and grays, with accent colors for emphasis
避免元素:
Cluttered design, realistic photos, complex 3D rendering
這是最安全的部署方式,將 public/ 設為網站根目錄。
步驟一:上傳專案到非公開目錄
- 登入 cPanel → 檔案管理員
- 在
home目錄下建立新資料夾,例如my-ci4-app - 上傳壓縮檔並解壓縮
目錄結構應該是:
/home/username/
├── my-ci4-app/ # CI4 專案(非公開)
│ ├── app/
│ ├── public/
│ ├── writable/
│ └── ...
├── public_html/ # 原本的網站根目錄
└── ...
步驟二:設定網站根目錄指向 public
方式 A:使用 cPanel 的「子網域」或「附加網域」
- cPanel → 子網域(或附加網域)
- 文件根目錄設定為:
/home/username/my-ci4-app/public
方式 B:修改主網域的根目錄
如果主機商支援,可以直接修改主網域的根目錄指向。
方式 C:使用符號連結(部分主機支援)
# 透過 cPanel 終端機或 SSH
cd /home/username/public_html
ln -s ../my-ci4-app/public/* .
步驟三:設定 writable 目錄權限
writable/ 目錄需要可寫入權限:
- 檔案管理員 → 選擇
writable資料夾 - 權限 → 設定為
755或775 - 如果仍有問題,嘗試
777(不建議長期使用)
或透過 SSH:
chmod -R 755 /home/username/my-ci4-app/writable
步驟四:建立 .env 檔案
在專案根目錄建立 .env 檔案:
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = production
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
app.baseURL = 'https://your-domain.com/'
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_db_username
database.default.password = your_db_password
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
安全提醒:
- .env 檔案絕對不能放在 public/ 目錄
- 確認 .env 不會被直接存取(透過瀏覽器測試)
部署方式二:簡易部署
如果主機商不支援修改網站根目錄,可以使用這個變通方案。
步驟一:調整 index.php 路徑
將整個專案上傳到 public_html/,但修改 public/index.php:
<?php
// public/index.php
// 修改這兩行的路徑
$pathsPath = FCPATH . '../app/Config/Paths.php';
// 改為
$pathsPath = FCPATH . 'app/Config/Paths.php';
步驟二:移動 public 內容到根目錄
目錄結構變成:
/home/username/public_html/
├── app/
├── writable/
├── vendor/
├── index.php # 從 public/ 移出
├── .htaccess # 從 public/ 移出
├── css/
├── js/
└── .env
步驟三:更新 Paths.php
編輯 app/Config/Paths.php:
<?php
namespace Config;
class Paths
{
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
public string $appDirectory = __DIR__ . '/../';
public string $writableDirectory = __DIR__ . '/../../writable';
public string $testsDirectory = __DIR__ . '/../../tests';
public string $viewDirectory = __DIR__ . '/../Views';
}
步驟四:保護敏感目錄
在 app/、writable/、vendor/ 目錄下各建立 .htaccess:
# app/.htaccess
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
💡 cPanel 設定卡關?
目錄權限、.htaccess 設定、PHP 版本切換,這些細節容易出錯。
預約免費諮詢,讓工程師幫你處理 cPanel 部署。
.htaccess 設定詳解

插圖:.htaccess URL 重寫規則示意圖
場景描述:
Technical illustration showing .htaccess URL 重寫規則示意圖. Clean, professional diagram style.
視覺重點:
- Clear presentation of the concept
- Professional technical diagram style
- Easy to understand visual elements
必須出現的元素:
- Relevant technical components
- Clear labels and annotations
- Logical flow or structure
需要顯示的中文字:
無
風格:
Clean flat design, technical illustration, modern infographic style
顏色調性:
Professional blues and grays, with accent colors for emphasis
避免元素:
Cluttered design, realistic photos, complex 3D rendering
.htaccess 是 Apache 的分散式設定檔,對於 CI4 部署至關重要。
標準 .htaccess(public 目錄)
# public/.htaccess
# 禁止目錄列表
Options -Indexes
# 開啟 URL 重寫
<IfModule mod_rewrite.c>
RewriteEngine On
# 設定基礎路徑(如果在子目錄,需調整)
# RewriteBase /subfolder/
# 如果檔案或目錄存在,直接提供
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 其他請求導向 index.php
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
# 設定預設字元編碼
AddDefaultCharset UTF-8
# 禁止存取隱藏檔案
<FilesMatch "^\.">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Deny from all
</IfModule>
</FilesMatch>
# 設定快取(可選)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
URL 重寫的作用
| 原始 URL | 重寫後 | 說明 |
|---|---|---|
/products/123 |
index.php/products/123 |
移除 index.php |
/about |
index.php/about |
乾淨的 URL |
/css/style.css |
直接提供檔案 | 靜態資源不重寫 |
常見問題排解
問題一:mod_rewrite 沒有啟用
症狀:URL 重寫無效,出現 404
解決:
1. 聯繫主機商確認是否支援
2. 嘗試在 .htaccess 加入 RewriteEngine On
問題二:Internal Server Error (500)
症狀:網站完全無法存取
解決:
1. 檢查 .htaccess 語法是否正確
2. 逐行註解找出問題行
3. 查看 error_log
問題三:RewriteBase 設定錯誤
如果網站在子目錄(如 your-domain.com/myapp/):
RewriteBase /myapp/
資料庫設定
步驟一:在 cPanel 建立資料庫
- cPanel → MySQL 資料庫
- 建立新資料庫:
username_ci4db - 建立新使用者:
username_ci4user - 將使用者加入資料庫,勾選「所有權限」
步驟二:設定 .env
database.default.hostname = localhost
database.default.database = username_ci4db
database.default.username = username_ci4user
database.default.password = your_secure_password
database.default.DBDriver = MySQLi
database.default.port = 3306
步驟三:匯入資料
方式 A:phpMyAdmin
- cPanel → phpMyAdmin
- 選擇資料庫
- 匯入 → 選擇 SQL 檔案
方式 B:使用 CI4 Migrations
如果你有設定 Migrations,可以透過瀏覽器觸發:
// 建立一個臨時 Controller(部署後刪除)
// app/Controllers/Migrate.php
namespace App\Controllers;
class Migrate extends BaseController
{
public function index()
{
$migrate = \Config\Services::migrations();
try {
$migrate->latest();
return 'Migrations completed!';
} catch (\Exception $e) {
return 'Migration failed: ' . $e->getMessage();
}
}
}
存取 https://your-domain.com/migrate 執行遷移,完成後刪除此 Controller。
環境設定與安全性

插圖:.env 檔案安全性提醒圖
場景描述:
Technical illustration showing .env 檔案安全性提醒圖. Clean, professional diagram style.
視覺重點:
- Clear presentation of the concept
- Professional technical diagram style
- Easy to understand visual elements
必須出現的元素:
- Relevant technical components
- Clear labels and annotations
- Logical flow or structure
需要顯示的中文字:
無
風格:
Clean flat design, technical illustration, modern infographic style
顏色調性:
Professional blues and grays, with accent colors for emphasis
避免元素:
Cluttered design, realistic photos, complex 3D rendering
生產環境 .env 完整範例
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = production
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
app.baseURL = 'https://your-domain.com/'
app.forceGlobalSecureRequests = true
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = username_ci4db
database.default.username = username_ci4user
database.default.password = your_secure_password
database.default.DBDriver = MySQLi
database.default.port = 3306
#--------------------------------------------------------------------
# ENCRYPTION
#--------------------------------------------------------------------
encryption.key = hex2bin:your_32_byte_hex_key_here
#--------------------------------------------------------------------
# SESSION
#--------------------------------------------------------------------
session.driver = 'CodeIgniter\Session\Handlers\DatabaseHandler'
session.savePath = 'ci_sessions'
#--------------------------------------------------------------------
# LOGGER
#--------------------------------------------------------------------
logger.threshold = 4
安全性檢查清單
| 項目 | 狀態 | 說明 |
|---|---|---|
| CI_ENVIRONMENT = production | ☐ | 關閉錯誤顯示 |
| .env 不在 public 目錄 | ☐ | 防止敏感資訊外洩 |
| app/ 目錄受保護 | ☐ | .htaccess 禁止存取 |
| writable/ 目錄受保護 | ☐ | .htaccess 禁止存取 |
| HTTPS 已啟用 | ☐ | SSL 憑證 |
| 資料庫密碼強度足夠 | ☐ | 至少 16 字元 |
| 預設 Controller 已刪除 | ☐ | 移除 Welcome Controller |
強制 HTTPS
在 .htaccess 加入:
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
或在 app/Config/App.php:
public bool $forceGlobalSecureRequests = true;
常見錯誤排解
錯誤一:Whoops! Something went wrong
原因:這是 CI4 的預設錯誤頁面,表示發生了未捕捉的異常。
排解步驟:
- 暫時設定
CI_ENVIRONMENT = development查看詳細錯誤 - 檢查
writable/logs/中的日誌 - 確認資料庫連線設定正確
- 確認檔案權限正確
錯誤二:404 Not Found(除了首頁)
原因:mod_rewrite 未正確運作
排解步驟:
- 確認
.htaccess存在且語法正確 - 確認主機支援
mod_rewrite - 嘗試在 URL 加入
index.php(如/index.php/about)
錯誤三:Class not found
原因:Composer 自動載入問題
排解步驟:
# 重新產生自動載入檔案
composer dump-autoload --optimize
錯誤四:Unable to write to cache
原因:writable/ 目錄權限不足
排解步驟:
chmod -R 755 writable/
# 如果還是不行
chmod -R 777 writable/
錯誤五:CSRF token mismatch
原因:跨站請求偽造保護觸發
排解步驟:
- 確認表單包含 CSRF token:
<?= csrf_field() ?> - 確認
app.baseURL設定正確 - 檢查 Session 是否正常運作
進階:其他部署選項
雖然 cPanel 是傳統選擇,但 PHP 也可以部署到現代平台:
Railway 部署
FROM php:8.2-apache
# 安裝擴展
RUN docker-php-ext-install mysqli pdo pdo_mysql
# 啟用 mod_rewrite
RUN a2enmod rewrite
# 複製專案
COPY . /var/www/html/
# 設定 Apache
RUN sed -i 's|/var/www/html|/var/www/html/public|g' /etc/apache2/sites-available/000-default.conf
# 權限
RUN chown -R www-data:www-data /var/www/html/writable
Docker Compose(本地開發)
version: '3.8'
services:
app:
build: .
ports:
- "8080:80"
volumes:
- .:/var/www/html
environment:
- CI_ENVIRONMENT=development
depends_on:
- db
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: ci4db
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
FAQ 常見問題
Q1: 如何更新已部署的網站?
- 在本地修改並測試
- 壓縮需要更新的檔案
- 上傳並覆蓋(注意不要覆蓋 .env)
- 如有資料庫變更,執行 migrations
Q2: writable 目錄一定要 777 嗎?
不建議長期使用 777。正確做法:
- 確認 writable 的擁有者是 web server 使用者(如 nobody、www-data)
- 設定 755 應該足夠
Q3: 如何設定多個網域?
- cPanel → 附加網域
- 每個網域指向不同的專案目錄
- 每個專案有獨立的 .env 設定
Q4: 可以用 Git 部署嗎?
部分 cPanel 支援 Git:
1. cPanel → Git 版本控制
2. 建立 Repository
3. 設定自動部署
Q5: 如何備份網站?
- cPanel → 備份精靈
- 選擇完整備份或部分備份
- 定期下載備份檔案
CodeIgniter 4 部署重點整理與安全檢查清單
這篇教學完整介紹了 CodeIgniter 4 部署到 cPanel 的流程:
- 目錄結構:理解 public 目錄的重要性
- 標準部署:將 public 設為網站根目錄(最安全)
- 簡易部署:適用於無法修改根目錄的主機
- .htaccess:URL 重寫與安全設定
- 資料庫:建立與連線設定
- 安全性:.env 保護與 HTTPS 設定
雖然 cPanel 虛擬主機看似簡單,但正確的部署方式對於網站安全至關重要。確保敏感檔案不對外公開,是最基本也最重要的原則。
如果你想了解更現代的部署方式,可以參考 Docker Deploy 教學 或 Node.js 部署教學。
🐘 PHP 部署需要協助?
從 cPanel 設定到效能優化,PHP 部署有許多細節需要注意。
預約免費諮詢,讓 VibeFix 的工程師幫你把 PHP 專案順利上線!