首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Apache mod_rewrite 實現 PHP 偽靜態完整指南

     編輯:PHP 相關知識

偽靜態技術能將動態 URL(如 index.php?action=page&id=18)轉換為靜態風格 URL(如 page-18.html),有利於 SEO、使用者記憶與分享。本文詳述 Apache mod_rewrite 模組的啟用、.htaccess 設定、重寫規則撰寫與 PHP 配合處理的完整流程。

步驟 1:確認並啟用 mod_rewrite 模組

# 1. 檢查是否已載入
php -i | grep "Loaded Modules"  # 或建立 phpinfo() 頁面搜尋 "mod_rewrite"

# 2. 若未啟用,編輯 httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so  # 移除行首 # 號

# 3. 重啟 Apache
sudo systemctl restart httpd  # 或 apachectl restart

步驟 2:允許 .htaccess 覆寫設定

在 httpd.conf 中找到網站根目錄對應的 <Directory> 區塊,修改 AllowOverride:

<Directory "/var/www/html">
    Options FollowSymLinks
    AllowOverride All  # 原為 None,改為 All 允許 .htaccess 生效
</Directory>

步驟 3:建立 .htaccess 與重寫規則

於網站根目錄建立 .htaccess(注意檔名以點開頭):

RewriteEngine On

# 規則 1:單一數字 ID → index.php?id=數字
RewriteRule ^([0-9]+)$ index.php?id=$1 [L]

# 規則 2:動作-編號.html → index.php?action=動作&id=編號
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]

# 旗標說明:
# L (Last)       : 停止後續規則處理
# QSA (QueryStringAppend) : 保留原查詢字串(如 ?foo=bar)並合併

步驟 4:PHP 端接收與處理參數

<?php
// index.php
$action = $_GET['action'] ?? 'default';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : 0;

echo "Action: {$action}
"; echo "ID: {$id}"; // 實際應用中可根據 action 分派控制器 switch ($action) { case 'page': showPage($id); break; case 'article': showArticle($id); break; default: showHome(); break; } ?>

進階規則範例與正則解析

需求RewriteRule說明
文章頁:/article/123.html^article/([0-9]+)\.html$固定前綴 + 數字 ID
分頁:/list-2.html^list-([0-9]+)\.html$對應 list.php?page=2
多參數:/product/cat-5/brand-3.html^product/cat-([0-9]+)/brand-([0-9]+)\.html$$1=分類ID, $2=品牌ID
中文標題:/post/標題-slug-456.html^post/([^/]+)-([0-9]+)\.html$[^/]+ 匹配非斜線字元(含中文)

常見問題與除錯技巧

  • 500 Internal Server Error:檢查 .htaccess 語法錯誤、AllowOverride 未設為 All、規則無限循環(善用 RewriteCond 排除實體檔案)。
  • 規則不生效:確認 RewriteEngine On、檔案權限正確(644)、Apache 已重啟。
  • CSS/JS/圖片 404:偽靜態 URL 層級較深(如 /article/123.html),導致相對路徑錯誤。解決:使用絕對路徑 /css/style.css 或 <base href="/">。
  • 除錯利器:啟用重寫日誌 RewriteLog "/var/log/apache2/rewrite.log" RewriteLogLevel 3(Apache 2.4+ 改用 LogLevel alert rewrite:trace3)。

Nginx 環境對應設定

若使用 Nginx,無 .htaccess,需在 server 區塊直接撰寫:

location / {
    try_files $uri $uri/ /index.php?$query_string;
    # 或具體規則:
    rewrite ^/([a-zA-Z]+)-([0-9]+)\.html$ /index.php?action=$1&id=$2 last;
}

總結

掌握 mod_rewrite 正則規則與旗標運用,是 PHP 開發者實現優雅 URL 的核心技能。建立規則時遵循「由具體到一般」順序,善用 RewriteCond 排除實體資源,並搭配 PHP 路由機制,即可構建整潔、SEO 友善的 URL 架構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved