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

偽靜態 URL Rewrite 技術原理與 IIS/Apache 實戰配置

編輯:關於伺服器

URL Rewrite 核心只需兩項技能:正則表達式 與 Web 服務器配置。掌握後可實現動態頁面靜態化展示、SEO 優化、隱藏真實參數等效果。

IIS 環境配置 (ISAPI_Rewrite)

  1. 下載安裝 ISAPI_Rewrite (2.x 或 3.x),記住安裝路徑 (含 Rewrite.dll/ISAPI_Rewrite.dll)
  2. IIS 管理器 → 站點屬性 → ISAPI 篩選器 → 添加:
    • 篩選器名稱:Rewrite
    • 可執行文件:指向 DLL 文件
  3. 編輯配置文件 (httpd.ini 2.x / httpd.conf 3.x):
    [ISAPI_Rewrite]
    CacheClockRate 3600
    RewriteRule ^(.*)/([a-z0-9A-Z\-]+\.html)$ $1/default.asp\?id=$2
    關鍵正則符號:^ 行首、$ 行尾、\w 單詞字符、\s 空白、+ ≥1 次、* ≥0 次、[...] 字符集、(...) 分組捕獲

Apache 環境配置 (mod_rewrite + .htaccess)

  1. 編輯 httpd.conf,修改兩處:
    • 目錄權限:AllowOverride None → AllowOverride All (允許 .htaccess 覆蓋)
    • 載入模組:取消註釋 LoadModule rewrite_module modules/mod_rewrite.so
  2. 重啟 Apache:apachectl restart
  3. 站點根目錄創建 .htaccess:
    RewriteEngine On
    RewriteRule ^([a-z0-9A-Z\-]+\.html)$ default.php\?id=$1

正則表達式速查表

符號含義示例匹配
^字符串開始^abc 匹配 "abc..."
$字符串結束abc$ 匹配 "...abc"
.任意單字符a.c 匹配 "abc", "axc"
\w字母數字下劃線等同 [a-zA-Z0-9_]
\d數字等同 [0-9]
\s空白字符空格、制表、換行
*零次或多次ab*c 匹配 "ac", "abc", "abbc"
+一次或多次ab+c 匹配 "abc", "abbc"
?零次或一次ab?c 匹配 "ac", "abc"
(...)捕獲分組反向引用 $1, $2...
(?:...)非捕獲分組僅分組不捕獲

驗證測試

瀏覽器訪問 https://domain.com/test-123.html,應正確路由至 default.php?id=test-123 並能通過 $_GET['id'] 獲取參數。Apache 環境可用 RewriteLog 調試 (需配置日誌級別)。

現代部署建議:IIS 7+ 使用原生 URL Rewrite Module (配置 web.config);Apache 2.4+ 優先使用 <Directory> 直接配置避免 .htaccess 性能損耗;Nginx 使用 rewrite 指令原生支持。
Copyright © Windows教程網 All Rights Reserved