CodeIgniter(CI)預設 URL 格式為 example.com/index.php/controller/method,index.php 影響美觀與 SEO 友善度。本文提供標準移除方案。
mod_rewrite 模組AllowOverride All(支援 .htaccess)專案根目錄(與 index.php 同層)建立 .htaccess:
RewriteEngine On
RewriteBase /
# 排除實體存在的檔案/目錄(圖片、CSS、JS、robots.txt 等)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 排除特定資源路徑
RewriteCond $1 !^(index\.php|assets|images|css|js|robots\.txt|favicon\.ico)
# 重寫至 index.php
RewriteRule ^(.*)$ index.php/$1 [L]
| 指令 | 說明 |
|---|---|
RewriteCond %{REQUEST_FILENAME} !-f | 請求非實體檔案 |
RewriteCond %{REQUEST_FILENAME} !-d | 請求非實體目錄 |
RewriteCond $1 !^(...) | 排除靜態資源路徑,避免被重寫導致 404 |
RewriteRule ^(.*)$ index.php/$1 [L] | 捕獲路徑傳給 index.php,[L] 結束重寫 |
編輯 application/config/config.php:
$config['index_page'] = ''; // 原為 'index.php'
$config['uri_protocol'] = 'REQUEST_URI'; // 建議值:AUTO / REQUEST_URI / PATH_INFO
$config['base_url'] = 'https://your-domain.com/'; // 完整網址結尾加斜線
若使用 Nginx,需在 server 區塊加入:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
https://your-domain.com/controller/method 應正常運作mod_rewrite 是否啟用、AllowOverride 設定CI 4 專案結構不同,index.php 位於 public/ 目錄,.htaccess 應放在 public/,且 baseURL 設定於 app/Config/App.php。