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

CodeIgniter 移除 URL 中 index.php 的完整配置教學

     編輯:PHP 相關知識

CodeIgniter 預設 URL 包含 index.php (如 /index.php/controller/method),透過 Apache mod_rewrite 可實現美觀的無縫 URL。

步驟一:啟用 Apache mod_rewrite

# httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so

移除行首 # 啟用模組,重啟 Apache。

步驟二:允許 .htaccess 覆蓋

# httpd.conf - 找到對應目錄區塊
AllowOverride All

將 AllowOverride None 改為 All,允許 .htaccess 生效。

步驟三:建立 .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)

步驟四:修改 CI 配置

# application/config/config.php
$config['index_page'] = '';  // 原為 'index.php'

# 可選:設定 URI 協定 (AUTO/REQUEST_URI/QUERY_STRING/PATH_INFO)
$config['uri_protocol'] = 'REQUEST_URI';

步驟五:重啟 Apache 驗證

# 測試
https://yourdomain.com/controller/method
https://yourdomain.com/welcome  # 預設控制器

Nginx 環境配置

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 Foundmod_rewrite 未啟用檢查 LoadModule、重啟 Apache
500 Internal Error.htaccess 語法錯誤檢查 RewriteRule 正則、編碼
CSS/JS/圖片 404靜態檔被重寫RewriteCond 排除靜態目錄
子目錄無效RewriteBase 錯誤調整 RewriteRule 路徑前綴
無限重導向規則匹配自身確認 RewriteCond 排除 index.php

進階:強制 HTTPS + 移除 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]
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved