CodeIgniter 預設 URL 含 index.php(如 example.com/index.php/controller/method),影響美觀與 SEO。透過 Web Server 重寫規則可移除它,獲得乾淨 RESTful 風格 URL(example.com/controller/method)。
mod_rewrite 已啟用:sudo a2enmod rewrite && systemctl reload apache2。index.php 同層)建立/編輯 .htaccess:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# 排除實體存在的檔案/目錄
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 重寫至 index.php
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>
RewriteBase /:若專案在子目錄(如 /ci/),改為 RewriteBase /ci/。QSA (Query String Append):保留原查詢字串(?foo=bar)。L (Last):匹配後停止後續規則。server {
listen 80;
server_name example.com;
root /var/www/ci/public; # CI4 指向 public;CI3 指向專案根目錄
index index.php;
location / {
# 嘗試直接服務檔案,否則重寫至 index.php
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_intercept_errors on;
}
}
CI3 特別注意:root 指向專案根目錄(含 index.php),try_files 同樣適用。
IIS 7+ 使用 web.config 定義重寫規則:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="CodeIgniter Rewrite" stopProcessing="true">
<match url="^(.*)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
$config['index_page'] = ''; // 空字串 $config['uri_protocol'] = 'REQUEST_URI'; // 推薦
public $indexPage = ''; public $uriProtocol = 'REQUEST_URI';
| 現象 | 排查步驟 |
|---|---|
| 404 Not Found | 1. 確認 .htaccess/web.config 生效(Apache 需 AllowOverride All) 2. 檢查 CI config 中 index_page 確為空 3. 確認控制器/方法命名符合規範(首字大寫) |
| No input file specified | Nginx/IIS fastcgi_param SCRIPT_FILENAME 路徑錯誤,需指向實際 index.php 絕對路徑 |
| CSS/JS/圖片 404 | 靜態資源未排除重寫,確認 RewriteCond !-f 生效;Nginx try_files 順序正確 |
| 子目錄部署 | Apache: RewriteBase /subdir/;Nginx: location /subdir/ { try_files ... /subdir/index.php... } |
移除 index.php 是 CodeIgniter 專案上線的標準動作。掌握 Apache/Nginx/IIS 三大主流伺服器的重寫規則,並搭配框架內部配置,即可獲得乾淨、專業的 URL 結構,提升 SEO 與用戶體驗。