Apache 的 `mod_rewrite` 模組配合 `.htaccess` 是 PHP 專案實現 URL 靜態化的標準方案。本文涵蓋模組啟用、.htaccess 建立、重寫規則撰寫與常見範例。
Loaded Modules 是否含 mod_rewrite;編輯 `httpd.conf`,找到網站目錄對應的 `
Options FollowSymLinks
AllowOverride All # 原為 None,改為 All
重啟 Apache 生效。
Windows 下無法直接建立無檔名檔案,三種方法:
.htaccess(含引號);<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index.html$ index.php
RewriteRule ^new-(\d+).html$ newxx.php?uid=$1
</IfModule>
RewriteEngine On:啟用重寫引擎;RewriteRule:模式 → 目標,支援正則、捕獲組 `$1` `$2`...;^ 開頭、`$` 結尾、`\d+` 一個以上數字、`(.*)` 任意字元;[L] 最後一條、`[R=301]` 外部重導向、`[NC]` 忽略大小寫、`[QSA]` 附加查詢字串。<IfModule mod_rewrite.c>
RewriteEngine On
# 靜態首頁
RewriteRule ^index\.html$ index.php [L]
# 文章詳情
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L]
# 分類列表分頁
RewriteRule ^category/([a-z0-9-]+)/page/([0-9]+)/?$ category.php?slug=$1&page=$2 [L]
# 移除 .php 副檔名
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 強制 www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# 防盜鏈
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ /nohotlink.jpg [R=301,L]
</IfModule>
`.htaccess` 雖方便但每請求都會讀取,高流量站建議將規則寫入 `httpd.conf` / `vhost.conf` 並設 `AllowOverride None` 提升效能。