偽靜態是將動態 URL(如 index.php?id=1&page=2)偽裝成靜態頁面形式(如 article-1-2.html 或 /article/1/2)的技術。本文系統講解偽靜態原理、Apache/Nginx 重寫規則、PHP 代碼級路由解析三大實現層面,並對比優缺點。
偽靜態本質上包含兩個階段:
index.php?params),**瀏覽器地址欄不變**$_SERVER['REQUEST_URI'] 或 $_GET 參數,分發到對應控制器mod_rewrite 模塊AllowOverride All 允許 .htaccess 覆蓋RewriteEngine On
# 1. 排除真實存在的文件/目錄(圖片、CSS、JS 直接訪問)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 2. 核心重寫:所有請求轉發到 index.php,原路徑作為參數
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
# 針對特定格式的精確規則示例:
# article-123.html → index.php?action=article&id=123
RewriteRule ^article-([0-9]+)\.html$ index.php?action=article&id=$1 [L]
# page-5.html → index.php?page=5
RewriteRule ^page-([0-9]+)\.html$ index.php?page=$1 [L]
# 多參數:category-php-page-2.html → index.php?cat=php&page=2
RewriteRule ^category-([a-z]+)-page-([0-9]+)\.html$ index.php?cat=$1&page=$2 [L]
$1 對應第一個 (...),$2 對應第二個...[L] (Last) 停止後續規則匹配[QSA] (Query String Append) 保留原查詢字串server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php;
location / {
# 核心:嘗試文件、目錄、最後回退到 index.php 帶參數
try_files $uri $uri/ /index.php?$query_string;
# 等價於 Apache 的:
# if (!-f $request_filename) {
# rewrite ^/(.*)$ /index.php?route=$1 last;
# }
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
Nginx try_files 比 Apache RewriteRule 更高效、語義更清晰,推薦優先使用。
若無法修改 Web 伺服器配置(如共享主機),可在 PHP 入口文件解析 REQUEST_URI:
<?php
// 訪問:https://example.com/index.php/article/123
$pathInfo = $_SERVER['PATH_INFO'] ?? ''; // /article/123
$pathInfo = trim($pathInfo, '/');
$segments = explode('/', $pathInfo); // ['article', '123']
$controller = $segments[0] ?? 'index';
$action = $segments[1] ?? 'index';
$id = $segments[2] ?? null;
// 分發
require "controllers/{$controller}.php";
?>
<?php
$requestUri = $_SERVER['REQUEST_URI']; // /index.php/article/123?foo=bar
// 1. 去除查詢字串
$path = parse_url($requestUri, PHP_URL_PATH); // /index.php/article/123
// 2. 去除入口腳本名
$scriptName = $_SERVER['SCRIPT_NAME']; // /index.php
$routePath = substr($path, strlen($scriptName)); // /article/123
$routePath = trim($routePath, '/');
// 3. 解析路由
if ($routePath === '') {
$controller = 'index'; $action = 'index';
} else {
$segments = explode('/', $routePath);
$controller = $segments[0];
$action = $segments[1] ?? 'index';
$params = array_slice($segments, 2);
}
// 4. 兼容傳統 ?id=1 參數
$_GET = array_merge($_GET, array_combine(['id', 'page', 'action'], $params));
?>
<?php
$routes = [
'GET /' => ['HomeController', 'index'],
'GET /article/{id:\d+}' => ['ArticleController', 'show'],
'POST /article' => ['ArticleController', 'store'],
'GET /category/{slug}' => ['CategoryController', 'index'],
];
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
foreach ($routes as $pattern => $handler) {
[$routeMethod, $routePath] = explode(' ', $pattern, 2);
if ($method !== $routeMethod) continue;
// 將 {param:regex} 轉換為正則
$regex = preg_replace('/\{(\w+)(?::([^}]+))?\}/', '(?P<$1>$2)', $routePath);
$regex = '@^' . $regex . '$@';
if (preg_match($regex, $path, $matches)) {
// 過濾數字索引,保留命名捕獲組
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
[$controller, $action] = $handler;
// 實例化控制器、調用方法、注入參數...
break;
}
}
?>
| 維度 | 偽靜態 | 真靜態 (生成 HTML) | 前後端分離 (SPA/SSR) |
|---|---|---|---|
| URL 形式 | /article/123.html | /article/123.html (實際文件) | /article/123 (前端路由) /api/article/123 |
| 服務端壓力 | 每請求執行 PHP | 極低(直接發送文件) | API 請求執行 PHP/Node/Go |
| 數據實時性 | 實時 | 需重新生成 | 實時 |
| SEO 友好度 | 高 | 最高 | SSR 高,CSR 需預渲染 |
| 部署複雜度 | 低(需 Rewrite) | 中(生成部署流程) | 高(構建、節點、SSR) |
| 適用場景 | 內容型站點、SEO 敏感、中小流量 | ||
$_GET/$_REQUESTRewriteRule + QSA 旗標try_files $uri $uri/ /index.php?$query_string 一行搞定REQUEST_URI、PATH_INFO、正則路由表掌握三層實現方式,根據部署環境靈活選擇,讓 URL 既漂亮又可控。