Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 2.x URL 重寫完整指南:模塊配置、規則編寫與 vBulletin/Drupal 實戰案例

編輯:關於伺服器

核心模塊:mod_rewrite

URL 重寫由 `mod_rewrite.so` 實現。需確認:

  1. 編譯/安裝包含該模塊。
  2. `httpd.conf` 載入:`LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so` (路徑視發行版)。
  3. 啟用驗證:`httpd -M` 輸出含 `rewrite_module (shared)`。

Directory 基線配置 (關鍵)


DocumentRoot /opt/www

    Options FollowSymLinks
    AllowOverride All          # 允許 .htaccess 覆蓋
    Order allow,deny
    Allow from all

`AllowOverride All` 讓 Apache 讀取各站點目錄下 `.htaccess` 實現分佈式重寫規則。

重啟生效


# Slackware      /etc/rc.d/rc.httpd restart
# Ubuntu/Debian  /etc/init.d/apache2 restart
# RHEL/CentOS    /etc/init.d/httpd restart

實戰案例一:vBulletin 3.5+ 偽靜態規則 (.htaccess)


Options +FollowSymLinks
RewriteEngine on

# 搜索/每日/無回覆
RewriteRule ^getdaily\.html$ search.php?do=getdaily [L]
RewriteRule ^getdaily([0-9]+)\.html$ search.php?do=getdaily&f=$1 [L]
RewriteRule ^unanswered\.html$ search.php?do=process&replyless=1&replylimit=0&dontcache=1 [L]
RewriteRule ^unanswered([0-9]+)\.html$ search.php?do=process&replyless=1&replylimit=0&dontcache=1&forumchoice=$1&childforums=1 [L]

# 版塊/公告/主題/帖子
RewriteRule ^forum([0-9]+)\.html$ forumdisplay.php?f=$1 [L]
RewriteRule ^forum([0-9]+)-([0-9]+)-([a-z]+)-(.*)-([0-9]+)-(.*)\.html$ forumdisplay.php?f=$1&page=$2&sort=$3&order=$4&pp=$5&daysprune=$6 [L]
RewriteRule ^announcement([0-9]+)\.html$ announcement.php?f=$1 [L]
RewriteRule ^thread([0-9]+)\.html$ showthread.php?t=$1 [L]
RewriteRule ^thread([0-9]+)-([0-9]+)\.html$ showthread.php?t=$1&page=$2 [L]
RewriteRule ^post([0-9]+)\.html$ showthread.php?p=$1 [L]
RewriteRule ^post([0-9]+)-([0-9]+)\.html$ showpost.php?p=$1&postcount=$2 [L]
... (更多規則見原文)

配套 XML 插件:導入 `vbburlhack.xml` 替換模板輸出鏈接為靜態格式,實現前後端一致。

實戰案例二:Drupal Clean URLs

  1. 安裝包自帶 `.htaccess` (含 `RewriteEngine on` + 核心規則)。
  2. 後台 → 管理 → 站點配置 → Clean URLs → 「執行測試」→ 通過後啟用。
  3. 若測試失敗:檢查 `.htaccess` 是否丟失、`AllowOverride All` 是否生效、`mod_rewrite` 是否載入。

避坑指南

  • .htaccess 位置:必須在站點 DocumentRoot 根目錄,非子目錄。
  • 權限:Apache 進程用戶需讀取權限 (通常 644)。
  • 規則衝突:多應用共存時,主配置 `RewriteRule` 與 `.htaccess` 可能衝突,建議統一管理或隔離 VirtualHost。
  • 性能:`.htaccess` 每請求遍歷目錄樹讀取,高併發建議將規則寫入主配置 `` 並關閉 `AllowOverride`。

結語

Apache URL 重寫三步走:載入模塊 → Directory AllowOverride All → 編寫規則 (.htaccess 或主配置)。vBulletin 需手工規則 + XML 插件雙管齊下;Drupal 開箱即用。乾淨 URL 不僅利於 SEO (Google 更快收錄),更能屏蔽內部技術細節、提升安全性與可維護性。建議所有公開站點強制啟用 Clean URLs。

Copyright © Windows教程網 All Rights Reserved