CodeIgniter 預設 URL 包含 index.php (如 /index.php/controller/method),透過 Apache mod_rewrite 可實現美觀的無縫 URL。
# httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so
移除行首 # 啟用模組,重啟 Apache。
# httpd.conf - 找到對應目錄區塊
AllowOverride All
將 AllowOverride None 改為 All,允許 .htaccess 生效。
在 CI 專案根目錄 (與 index.php 同層) 建立 .htaccess:
RewriteEngine On
RewriteCond $1 !^(index\.php|images|robots\.txt|css|js)
RewriteRule ^(.*)$ /index.php/$1 [L]
若專案在子目錄 (如 /CodeIgniter/):
RewriteRule ^(.*)$ /CodeIgniter/index.php/$1 [L]
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|assets|uploads)
# application/config/config.php
$config['index_page'] = ''; // 原為 'index.php'
# 可選:設定 URI 協定 (AUTO/REQUEST_URI/QUERY_STRING/PATH_INFO)
$config['uri_protocol'] = 'REQUEST_URI';
# 測試
https://yourdomain.com/controller/method
https://yourdomain.com/welcome # 預設控制器
server {
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
| 現象 | 原因 | 解決 |
|---|---|---|
| 404 Not Found | mod_rewrite 未啟用 | 檢查 LoadModule、重啟 Apache |
| 500 Internal Error | .htaccess 語法錯誤 | 檢查 RewriteRule 正則、編碼 |
| CSS/JS/圖片 404 | 靜態檔被重寫 | RewriteCond 排除靜態目錄 |
| 子目錄無效 | RewriteBase 錯誤 | 調整 RewriteRule 路徑前綴 |
| 無限重導向 | 規則匹配自身 | 確認 RewriteCond 排除 index.php |
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond $1 !^(index\.php|assets|uploads|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]