ThinkPHP 提供四種 URL 訪問模式,配合 Apache/Nginx 重寫可實現優雅的 RESTful 風格 URL。本文系統整理模式差異、設定步驟與避坑指南。
PATHINFO 模式下,URL 參數以路徑形式傳遞:
# 等價請求
https://localhost/index.php?m=Index&a=test
https://localhost/index.php/Index/test
| 值 | 模式名稱 | URL 範例 | 特點 |
|---|---|---|---|
| 0 | 普通模式 | ?m=Module&a=Action | 相容性最好、URL 醜陋、SEO 差 |
| 1 | PATHINFO | /Module/Action | 語義清晰、無需 Server 設定、預設推薦 |
| 2 | REWRITE (偽靜態) | /Module/Action (無 index.php) | 最美觀、需 Web Server 重寫規則、SEO 最佳 |
| 3 | 相容模式 | ?s=Module/Action | 不支援 PATHINFO 的 Server 替代方案 |
// Conf/config.php 或 Conf/convention.php 'URL_MODEL' => 2, // 設定為 REWRITE 模式
httpd.conf,確保載入 mod_rewrite:LoadModule rewrite_module modules/mod_rewrite.so.htaccess 覆寫:AllowOverride All(將 None 改為 All).htaccess:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
}
}
https://domain.com/Module/Action(無 index.php)正常顯示頁面。$_SERVER['PATH_INFO'] 正確解析。| 模式 | 效能 | SEO | 維護性 | 建議場景 |
|---|---|---|---|---|
| 普通 (0) | 最快 | 差 | 簡單 | 內部 API、管理後台 |
| PATHINFO (1) | 快 | 良 | 簡單 | 大多數專案預設選擇 |
| REWRITE (2) | 略慢 (重寫開銷) | 最佳 | 需 Server 維護 | 前台展示站、SEO 敏感專案 |
| 相容 (3) | 快 | 良 | 簡單 | 舊版 Server、虛擬主機受限環境 |
mod_rewrite 未開啟、AllowOverride 未設為 All、.htaccess 路徑錯誤。RewriteCond 排除實體檔案/目錄。URL_MODEL 設定生效、PATH_INFO 變數正確。根據專案階段與部署環境選擇適當模式:開發期用 PATHINFO (1),正式上線關鍵前台頁面升級 REWRITE (2),後台管理可維持 PATHINFO 或普通模式。