首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CodeIgniter 移除 URL 中 index.php 完整教學:.htaccess 重寫規則與配置修改

     編輯:PHP 相關知識

問題背景

CodeIgniter(CI)預設 URL 格式為 example.com/index.php/controller/method,index.php 影響美觀與 SEO 友善度。本文提供標準移除方案。

前置條件

  • Apache 啟用 mod_rewrite 模組
  • 虛擬主機/目錄允許 AllowOverride All(支援 .htaccess)
  • CI 版本 3.x / 4.x 均適用

步驟一:建立 .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] 結束重寫

步驟二:修改 CI 設定檔

編輯 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 環境配置

若使用 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;
}

驗證與除錯

  1. 訪問 https://your-domain.com/controller/method 應正常運作
  2. 若 404:檢查 mod_rewrite 是否啟用、AllowOverride 設定
  3. 若 500:檢查 .htaccess 語法、錯誤日誌
  4. 靜態資源 404:確認排除規則包含該資源目錄

CI 4.x 差異提醒

CI 4 專案結構不同,index.php 位於 public/ 目錄,.htaccess 應放在 public/,且 baseURL 設定於 app/Config/App.php。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved