URL 靜態化 (偽靜態) 能改善 SEO、美化連結、隱藏技術細節。Apache 透過 mod_rewrite 模組實現。本文詳解獨立主機與虛擬主機兩種場景的配置方法,並提供三大熱門 PHP 產品的完整規則集。
httpd.conf 需有 LoadModule rewrite_module libexec/mod_rewrite.so 及 AddModule mod_rewrite.chttpd.conf 需有 LoadModule rewrite_module modules/mod_rewrite.so--enable-rewrite=shared 或動態載入模組。原則: 規則必須寫在對應的 <VirtualHost> 區塊內,寫在外層可能不生效。修改後 必須重啟 Apache。
<IfModule mod_rewrite.c>
RewriteEngine On
# Discuz! 6.1.0 規則範例
RewriteRule ^(.*)/archiver/((fid|tid)-[\w-]+\.html)$ $1/archiver/index.php?$2
RewriteRule ^(.*)/forum-([0-9]+)-([0-9]+)\.html$ $1/forumdisplay.php?fid=$2&page=$3
RewriteRule ^(.*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/viewthread.php?tid=$2&extra=page%3D$4&page=$3
RewriteRule ^(.*)/space-(username|uid)-(.+)\.html$ $1/space.php?$2=$3
RewriteRule ^(.*)/tag-(.+)\.html$ $1/tag.php?name=$2
</IfModule>
前提: 主機商必須支援 AllowOverride All (或至少 FileInfo) 並允許解析 .htaccess。請先諮詢確認。
.htaccess (Windows 下可從其他系統複製或下載空白檔)。RewriteBase 指向安裝子目錄 (根目錄則為 /)。RewriteEngine On
RewriteBase /discuz # 修改為你的實際安裝目錄,根目錄改為 /
# Discuz! 系統規則
RewriteRule ^archiver/((fid|tid)-[\w-]+\.html)$ archiver/index.php?$1
RewriteRule ^forum-([0-9]+)-([0-9]+)\.html$ forumdisplay.php?fid=$1&page=$2
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ viewthread.php?tid=$1&extra=page%3D$3&page=$2
RewriteRule ^space-(username|uid)-(.+)\.html$ space.php?$1=$2
RewriteRule ^tag-(.+)\.html$ tag.php?name=$1
保存上傳後,進入論壇後台「搜尋引擎優化」開啟 URL 靜態化功能。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^/([0-9]+)/spacelist(.+)$ /index.php?uid/$1/action/spacelist/type$2 [L]
RewriteRule ^/([0-9]+)/viewspace(.+)$ /index.php?uid/$1/action/viewspace/itemid$2 [L]
RewriteRule ^/([0-9]+)/viewbbs(.+)$ /index.php?uid/$1/action/viewbbs/tid$2 [L]
RewriteRule ^/([0-9]+)/(.*)$ /index.php?uid/$1/$2 [L]
RewriteRule ^/([0-9]+)$ /index.php?uid/$1 [L]
RewriteRule ^/action(.+)$ /index.php?action$1 [L]
RewriteRule ^/category(.+)$ /index.php?action/category/catid$1 [L]
RewriteRule ^/viewnews(.+)$ /index.php?action/viewnews/itemid$1 [L]
RewriteRule ^/viewthread(.+)$ /index.php?action/viewthread/tid$1 [L]
RewriteRule ^/mygroup(.+)$ /index.php?action/mygroup/gid$1 [L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/index\.html$ $1/index.php
RewriteRule ^(.*)/category$ $1/index.php [L]
RewriteRule ^(.*)/feed-c([0-9]+)\.xml$ $1/feed.php?cat=$2 [L]
RewriteRule ^(.*)/category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)-([0-9]+)-(.+)-([a-zA-Z]+)(.*).html$ $1/category.php?id=$2&brand=$3&price_min=$4&price_max=$5&filter_attr=$6&page=$7&sort=$8&order=$9
# ... 更多分類、商品、文章、品牌、標籤、搶購、團購規則請參考官方文檔
</IfModule>
RewriteLog "/var/log/apache2/rewrite.log"RewriteLogLevel 3 (1-9,生產環境建議關閉或設 1)。LogLevel alert rewrite:trace3RewriteBase 路徑錯誤導致規則不匹配。category-...-min-max-attr... 應在 category-... 之前)。. 必須寫成 \.。.htaccess 權限問題:檔案需可被 Apache 進程讀取 (通常 644)。