CodeIgniter 預設網址包含 index.php(如 example.com/index.php/controller/method),透過 Web Server 重寫規則可移除它,獲得更優雅的 RESTful 風格網址。本文詳細說明 Apache (.htaccess) 與 Nginx 兩種主流環境的設定步驟。
所有請求先導向 index.php,由框架路由器解析 URI 分派給對應 Controller/Method。移除 index.php 的本質是:當請求非實體檔案/目錄時,內部重寫到 index.php/$1。
.htaccess:RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|js|css|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
application/config/config.php:$config['index_page'] = ''; $config['base_url'] = 'https://yourdomain.com/'; // 含結尾斜線
mod_rewrite 並允許 AllowOverride All:# httpd.conf LoadModule rewrite_module modules/mod_rewrite.soAllowOverride All
若專案在子目錄 /subdir/,RewriteRule 需調整:
# 選項一:相對路徑(推薦) RewriteRule ^(.*)$ index.php/$1 [L] # 選項二:絕對路徑 RewriteRule ^(.*)$ /subdir/index.php/$1 [L]
server {
listen 80;
server_name yourdomain.com;
root /usr/share/nginx/www; # 專案根目錄
index index.php index.html index.htm;
location / {
# 核心重寫規則
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
break;
}
# 替代寫法:排除靜態資源
# if ($request_filename !~* (js|css|images|robots\.txt|index\.php)) {
# rewrite ^/(.*)$ /index.php/$1 last;
# }
}
location ~ \.php($|/) {
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_pass 127.0.0.1:9000; # php-fpm
fastcgi_index index.php;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 拒絕存取 .htaccess
location ~ /\.ht { deny all; }
}
base_url 結尾斜線、index_page 確為空字串、重寫規則路徑正確、mod_rewrite/Nginx 重寫模組已啟用。$this->load->helper('url'); echo current_url();https://domain.com/controller/method 正常顯示https://domain.com/index.php/controller/method 自動導向無 index.php 版本(可選)