ThinkPHP 的 Pathinfo 模式(URL_MODEL=2)配合 URL 重寫,能生成無 index.php 的優雅靜態化 URL,利於 SEO 且符合 REST 風格。本文詳解解析規則、重寫原理、Apache/Nginx 配置與常見坑點。
URL 結構:
https://domain/app.php/模塊/控制器/操作/參數1/值1/參數2/值2/...
$_GET;| 原始 URL | Pathinfo URL | 解析結果 |
|---|---|---|
/index.php/Blog/read/id/1 | /Blog/read/id/1 | 模塊=Blog, 控制器=read, 參數 id=1 |
/index.php/Api/v1/User/list/page/2/size/20 | /Api/v1/User/list/page/2/size/20 | 分組=Api, 模塊=v1, 控制器=User, 操作=list, page=2, size=20 |
Web 服務器將不存在的文件/目錄請求重定向到 index.php,由 PHP 框架接管路由解析。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# 除外真實存在的文件/目錄
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 重寫到 index.php,保留 PATH_INFO
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
QSA (Query String Append) 保留原查詢字串;PT (Pass Through) 傳遞給後續處理器(如 PHP);httpd.conf 載入 mod_rewrite 並允許 AllowOverride All。server {
listen 80;
server_name example.com;
root /var/www/html/public;
index index.php index.html;
location / {
# 嘗試文件、目錄、最後 fallback 到 index.php
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# 關鍵:支援 PATH_INFO
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
// config/app.php (TP6) 或 config/config.php (TP5)
'url_route_on' => true, // 開啟路由
'url_route_must' => false, // 強制路由(建議開發階段 false)
'url_convert' => true, // URL 自動轉換(駝峰轉下劃線)
'url_html_suffix' => '', // 去除 .html 後綴
// TP5 專用
'URL_MODEL' => 2, // Pathinfo 模式
'URL_ROUTER_ON' => true,
'URL_ROUTE_RULES' => [], // 自定義路由規則
| 現象 | 原因 | 解決 |
|---|---|---|
| 404 Not Found | 重寫模塊未載入 / .htaccess 未生效 | 檢查 mod_rewrite、AllowOverride、文件權限 |
| 參數無法獲取 | Nginx 未傳遞 PATH_INFO | 添加 fastcgi_split_path_info 規則 |
| CSS/JS/圖片 404 | 重寫規則攔截靜態資源 | 確保 RewriteCond !-f !-d 在前;Nginx try_files 順序正確 |
| 雙重 index.php | 生成 URL 仍含 index.php | 檢查 URL_MODEL=2、路由配置、框架版本差異 |
| 中文參數亂碼 | URL 編碼不一致 | 統一 UTF-8,Nginx 添加 charset utf-8; |
/api/v1/... 便於後續演進;掌握 Pathinfo + Rewrite 機制,能構建乾淨、可維護、SEO 友好的 URL 體系。