萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Apache mod_rewrite 實現 PHP 網址偽靜態完整教學

什麼是偽靜態

偽靜態 (URL Rewriting) 將動態 URL (如 index.php?action=page&id=18) 重寫為靜態風格 (如 page-18.html),利於 SEO、使用者體驗與安全性 (隱藏參數結構)。

三步驟啟用 Apache mod_rewrite

1. 開啟模組

# httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so
# 移除前面的 # 號,重啟 Apache

驗證:phpinfo() → Loaded Modules 應包含 mod_rewrite。

2. 允許 .htaccess 覆寫

# httpd.conf
<Directory "/var/www/html">
    Options FollowSymLinks
    AllowOverride All  # 原為 None,改為 All
</Directory>

3. 編寫 .htaccess 重寫規則

# .htaccess
RewriteEngine On

# 範例 1: 簡單數字 ID
RewriteRule ^([0-9]+)$ index.php?id=$1 [L]

# 範例 2: 偽靜態 HTML (action-id.html)
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L]

# 範例 3: 通用 MVC 路由 (所有非實體檔案導向 index.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

規則語法速查

符號含義
^字串開頭
$字串結尾
(...)捕獲群組,對應 $1, $2...
[a-zA-Z]字母範圍
[0-9]數字範圍
{1,}至少 1 次 (等同 +)
[L]Last,停止後續規則
[QSA]Query String Append,保留原查詢字串

PHP 端接收

<?php
// index.php
echo 'Action: ' . ($_GET['action'] ?? 'none') . '<br>';
echo 'ID: ' . ($_GET['id'] ?? 'none') . '<br>';

虛擬主機與 hosts 進階設定 (本地開發)

  1. httpd-vhosts.conf 新增 VirtualHost,指定 DocumentRoot 與 ServerName。
  2. C:\Windows\System32\drivers\etc\hosts 加入 127.0.0.1 myproject.local。
  3. 瀏覽器訪問 https://myproject.local/page-18.html 即可測試。

常見問題排查

  • 500 Internal Server Error:.htaccess 語法錯誤、AllowOverride 未開啟、RewriteEngine Off。
  • 404 Not Found:規則不匹配、REQUEST_FILENAME 判斷錯誤、未重啟 Apache。
  • 無限重導向:規則匹配到自身,需加 RewriteCond %{REQUEST_FILENAME} !-f 排除實體檔案。
copyright © 萬盛學電腦網 all rights reserved