偽靜態讓動態網址呈現靜態頁面樣貌 (如 /article/123.html),兼具 SEO 友善與動態彈性。本文詳細說明兩大主流實作方式:PATH_INFO 與 Web Server Rewrite。
PHP 內建支援 $_SERVER['PATH_INFO'] 取得腳本路徑後的額外路徑資訊。
https://example.com/index.php/article/123.html https://example.com/index.php/user/profile/456
<?php
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
// 範例:匹配 /article/123.html 格式
if (preg_match('~^(/[a-z]{1,16})\\.([0-9]{1,16})\\.html$~', $pathInfo, $matches)) {
// $matches[0] = 完整匹配 /article/123.html
// $matches[1] = /article
// $matches[2] = 123
$action = ltrim($matches[1], '/'); // 'article'
$id = (int)$matches[2]; // 123
// 當作 $_GET 使用
$_GET['action'] = $action;
$_GET['id'] = $id;
echo "Action: $action, ID: $id";
} else {
echo "404 Not Found";
}
?>
| 優點 | 缺點 |
|---|---|
| 無需修改 Apache/Nginx 設定 | 網址含 index.php 不夠美觀 |
| PHP 內建支援,相容性高 | 部分舊版 CGI/FastCGI 模式不支援 |
| 部署簡單,複製檔案即可 | 不利 SEO (搜尋引擎偏好乾淨網址) |
由 Web Server 將美觀網址內部重寫至 PHP 腳本,瀏覽器網址列保持乾淨。
RewriteEngine On
RewriteBase /
# 存在的檔案/目錄直接服務
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 核心重寫規則
# 範例:/article/123.html → index.php?action=article&id=123
RewriteRule ^([a-z]+)/([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]
# 通用規則:所有請求導向 index.php (前端控制器模式)
# RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 或特定規則
location ~ ^/([a-z]+)/([0-9]+)\.html$ {
rewrite ^/([a-z]+)/([0-9]+)\.html$ /index.php?action=$1&id=$2 last;
}
<?php
// index.php - 統一入口
$route = $_GET['route'] ?? $_SERVER['REQUEST_URI'];
// 解析路由
$routes = [
'article/(\d+)\.html' => 'ArticleController::show',
'user/(\d+)' => 'UserController::profile',
'category/([^/]+)' => 'CategoryController::list',
];
foreach ($routes as $pattern => $handler) {
if (preg_match('~^' . $pattern . '$~', $route, $matches)) {
array_shift($matches); // 移除完整匹配
// 呼叫控制器: call_user_func($handler, ...$matches)
echo "Handler: $handler, Params: " . implode(', ', $matches);
exit;
}
}
http_response_code(404);
echo "404 Not Found";
?>
| HTTP Method | URL | Controller Action | 說明 |
|---|---|---|---|
| GET | /articles | index | 文章列表 |
| GET | /articles/123 | show | 單篇文章 |
| POST | /articles | store | 新增文章 |
| PUT/PATCH | /articles/123 | update | 更新文章 |
| DELETE | /articles/123 | destroy | 刪除文章 |
/article/php-pseudo-static-guide- 分隔單字,非底線