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

CodeIgniter 移除 URL 中 index.php 完整指南:Apache 與 Nginx 設定

     編輯:PHP 相關知識

CodeIgniter URL 美化:移除 index.php 讓網址更乾淨

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。

Apache 環境設定 (.htaccess)

  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]
  1. 修改 application/config/config.php:
$config['index_page'] = '';
$config['base_url'] = 'https://yourdomain.com/'; // 含結尾斜線
  1. 確認 Apache 載入 mod_rewrite 並允許 AllowOverride All:
# httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so

    AllowOverride All

子目錄專案特別處理

若專案在子目錄 /subdir/,RewriteRule 需調整:

# 選項一:相對路徑(推薦)
RewriteRule ^(.*)$ index.php/$1 [L]

# 選項二:絕對路徑
RewriteRule ^(.*)$ /subdir/index.php/$1 [L]

Nginx 環境設定

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; }
}

常見坑點與驗證

Q: 設定後仍出現 404?
A: 檢查 base_url 結尾斜線、index_page 確為空字串、重寫規則路徑正確、mod_rewrite/Nginx 重寫模組已啟用。
Q: 靜態資源 (CSS/JS/圖片) 載入失敗?
A: 確認重寫條件排除靜態資源目錄,或將靜態資源放在獨立子域/CDN。
Q: 如何取得目前完整 URL?
A: 載入 URL Helper:$this->load->helper('url'); echo current_url();

驗證清單

  • ✅ https://domain.com/controller/method 正常顯示
  • ✅ https://domain.com/index.php/controller/method 自動導向無 index.php 版本(可選)
  • ✅ 靜態資源正常載入
  • ✅ 表單送出、分頁連結皆無 index.php
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved