偽靜態(URL Rewrite)讓動態 PHP 頁面呈現靜態 HTML 形式的 URL,利於 SEO、用戶體驗與安全性。主流方案有二:Web 服務器層面的 Rewrite(Apache/Nginx)與 PHP 內部的 PATH_INFO 解析。本文詳細對比兩種方案的配置與代碼實現。
編輯 httpd.conf,取消註釋:
LoadModule rewrite_module modules/mod_rewrite.so
並確保目錄允許覆蓋:AllowOverride All
在網站根目錄創建 .htaccess:
RewriteEngine On
# 根目錄訪問重寫到 index.php
RewriteRule ^$ index.php [L]
# 文章頁:article-123.html → article.php?id=123
RewriteRule ^article-([0-9]+)\.html$ article.php?id=$1 [L]
# 分頁:list-5-2.html → list.php?cid=5&page=2
RewriteRule ^list-([0-9]+)-([0-9]+)\.html$ list.php?cid=$1&page=$2 [L]
# 通用 REST 風格:/user/123/profile → index.php?m=user&id=123&a=profile
RewriteRule ^([a-z]+)/([0-9]+)/([a-z]+)$ index.php?m=$1&id=$2&a=$3 [L]
$1、$2... 對應正則中第 1、2 個 () 捕獲組[L] 旗標表示最後一條規則,匹配後停止後續匹配[NC] 不區分大小寫,[QSA] 追加原查詢字符串systemctl restart httpd # 或 apache2ctl restart
利用 $_SERVER['PATH_INFO'] 獲取腳本名之後的路徑信息。
https://example.com/soft.php/1,100,8630.html
// $_SERVER['PATH_INFO'] = '/1,100,8630.html'
<?php
if (isset($_SERVER['PATH_INFO'])) {
$pathInfo = $_SERVER['PATH_INFO']; // 如 /1,100,8630.html
// 正則提取參數
if (preg_match('#/(\d+),(\d+),(\d+)\.html#', $pathInfo, $matches)) {
$gid = (int)$matches[1]; // 1
$sid = (int)$matches[2]; // 100
$softid = (int)$matches[3]; // 8630
// 現在可像處理 $_GET 一樣使用
// 相當於 soft.php?gid=1&sid=100&softid=8630
} else {
die('Path: Error!');
}
} else {
die('Path: Nothing!');
}
?>
現代主流 Nginx 配置:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 特定規則
rewrite ^/article-(\d+)\.html$ /article.php?id=$1 last;
rewrite ^/list-(\d+)-(\d+)\.html$ /list.php?cid=$1&page=$2 last;
PATH_INFO 或框架內置路由Apache mod_rewrite 是偽靜態的工業標準,配置一次受益全站;PATH_INFO 是無服務器權限時的靈活備選。理解正則捕獲組映射、[L]/[QSA] 旗標含義、Nginx try_files 機制,能讓你在任何環境下優雅實現 SEO 友好的靜態化 URL。