ThinkPHP 預設 URL 包含 `index.php`(如 `/index.php/index/add`),啟用 `PATHINFO` 模式後需配合 Apache `mod_rewrite` 隱藏入口文件。本文提供標準配置步驟、虛擬主機寫法、常見失效原因與除錯技巧。
# 1. 確認 mod_rewrite 已載入
apachectl -M | grep rewrite
# 輸出應包含: rewrite_module (shared)
# 2. 確認 AllowOverride 允許 .htaccess
# httpd.conf 或虛擬主機配置中:
AllowOverride All
Require all granted
<?php
// config/app.php 或 application/config.php
return [
'url_route_on' => true,
'url_model' => 2, // PATHINFO 模式 (PATHINFO 2)
'url_html_suffix' => 'html', // 可選:偽靜態後綴
// ...
];
<IfModule mod_rewrite.c>
RewriteEngine On
# 如果不在網站根目錄,需設定 RewriteBase
# RewriteBase /subdir/
# 靜態資源直接通過
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# 其餘轉發至 index.php
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/project/public
<Directory /var/www/project/public>
Options -Indexes +FollowSymLinks
AllowOverride None # 關閉 .htaccess,直接在這裡寫規則
Require all granted
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
</Directory>
# 可選:HTTP → HTTPS 強制跳轉
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>
server {
listen 80;
server_name www.example.com;
root /var/www/project/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
| 現象 | 可能原因 | 排查步驟 |
|---|---|---|
| 404 Not Found | mod_rewrite 未啟用 | apachectl -M | grep rewrite;載入模組 `LoadModule rewrite_module modules/mod_rewrite.so` |
| 404 Not Found | AllowOverride None | 目錄配置改為 `AllowOverride All`,重啟 Apache |
| 404 Not Found | .htaccess 放錯位置 | 必須在 `public/` (入口文件目錄),非專案根目錄 |
| 404 Not Found | RewriteBase 錯誤 | 子目錄部署需 `RewriteBase /subdir/` |
| 500 Internal Server Error | .htaccess 語法錯誤 | 檢查 error_log;簡化規則測試 |
| 無限重導向 | 規則匹配自身 | 加入 `RewriteCond %{REQUEST_FILENAME} !-f` 排除實體檔案 |
| CSS/JS/圖片 404 | 靜態資源被轉發 | 確認 `RewriteCond %{REQUEST_FILENAME} -f` 在前 |
| PATH_INFO 為空 | PHP 版本/配置問題 | 檢查 `cgi.fix_pathinfo=1`,Nginx 需 `fastcgi_split_path_info` |
# 1. 測試 mod_rewrite 是否生效
# .htaccess 臨時加入:
RewriteEngine On
RewriteRule ^test$ /test.php [L]
# 訪問 /test 應顯示 test.php 內容
# 2. 開啟 RewriteLog (Apache 2.4+)
LogLevel alert rewrite:trace3
# error_log 會顯示詳細重寫過程
# 3. ThinkPHP 除錯模式
// config/app.php
'app_debug' => true,
'trace' => true,
# 檔案總管無法直接建立 .htaccess
# 方法一:命令提示字元
cd /d D:\www\project\public
copy NUL .htaccess
notepad .htaccess
# 方法二:新建文字文件 htaccess.txt,編輯後重命名
ren htaccess.txt .htaccess