偽靜態(URL Rewrite)是指將動態 URL(如 index.php?action=page&id=18)重寫為靜態頁面形式的 URL(如 page-18.html),實際仍由 PHP 腳本處理。優點:URL 友好、利於 SEO、隱藏技術細節、便於遷移。
phpinfo() → Loaded Modules 中是否有 mod_rewrite。若有則已啟用。httpd.conf,找到 #LoadModule rewrite_module modules/mod_rewrite.so,刪除前面的 #。LoadModule 區域末尾添加:LoadModule rewrite_module modules/mod_rewrite.so。編輯 httpd.conf,找到網站根目錄對應的 <Directory> 塊:
<Directory "/your/web/root">
Options FollowSymLinks
AllowOverride All # 將 None 改為 All
</Directory>
重啟 Apache 生效。
Windows 下無法直接創建以點開頭的文件,方法:
htaccess.txt。ren htaccess.txt .htaccess,或使用支持的編輯器(VS Code、Notepad++、Sublime)直接保存為 .htaccess。RewriteEngine On
RewriteRule 正則模式 目標URL [標誌]
RewriteEngine On:開啟重寫引擎。RewriteRule:匹配模式支持 PCRE 正則,目標 URL 中 $1、$2 對應捕獲組。[L] (Last, 停止後續規則)、[NC] (No Case, 忽略大小寫)、[QSA] (Query String Append, 保留原查詢字符串)。# 將 page-18.html 映射到 index.php?action=page&id=18
RewriteEngine On
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]
訪問 https://localhost/page-18.html 實際執行 index.php?action=page&id=18。
<?php
echo '你的 Action 是:' . htmlspecialchars($_GET['action'] ?? '');
echo '<br>';
echo '你的 ID 是:' . htmlspecialchars($_GET['id'] ?? '');
?>
RewriteEngine On
# 靜態資源直接訪問,不重寫
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# 文章詳情: article-123.html -> article.php?id=123
RewriteRule ^article-([0-9]+)\.html$ article.php?id=$1 [L,QSA]
# 分類列表: category-5.html -> category.php?cid=5
RewriteRule ^category-([0-9]+)\.html$ category.php?cid=$1 [L,QSA]
# 捕獲所有其他請求到入口文件 (MVC 框架常用)
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
AllowOverride 未設置。查看 Apache 錯誤日志。[L] 或使用 RewriteCond 排除。[QSA] 標誌保留原查詢字符串。Nginx 不支持 .htaccess,需在虛擬主機配置中直接編寫 rewrite 指令:
location / {
rewrite ^/([a-zA-Z]+)-([0-9]+)\.html$ /index.php?action=$1&id=$2 last;
# 前端控制器模式
try_files $uri $uri/ /index.php?$query_string;
}
掌握 mod_rewrite 正則規則編寫是 PHP 開發者必備技能。建議在開發環境充分測試,上線前進行壓力測試,確保重寫性能對吞吐量影響可控。