Apache mod_rewrite 偽靜態完整指南:從啟用到規則撰寫
mod_rewrite 是 Apache 強大的 URL 重寫模組,是偽靜態、URL 美化、反向代理、存取控制的核心工具。本文從模組啟用、基礎語法、實戰範例到除錯技巧完整說明。
一、啟用 mod_rewrite
1. 載入模組 (httpd.conf)
# 找到並取消註解
LoadModule rewrite_module modules/mod_rewrite.so
2. 允許 .htaccess 覆寫 (httpd.conf)
<Directory /var/www/html>
# 將 None 改為 All
AllowOverride All
</Directory>
3. 重啟 Apache
# Ubuntu/Debian
sudo systemctl restart apache2
# CentOS/RHEL
sudo systemctl restart httpd
二、.htaccess 基礎架構
# 必須第一行開啟引擎
RewriteEngine On
# 設定基礎路徑 (若 .htaccess 在子目錄需調整)
RewriteBase /
# 以下撰寫規則...
三、核心指令詳解
| 指令 |
功能 |
範例 |
RewriteRule |
核心重寫規則 |
RewriteRule ^page/(\d+)$ index.php?page=$1 |
RewriteCond |
條件判斷 (可多行,預設 AND) |
RewriteCond %{REQUEST_FILENAME} !-f |
RewriteBase |
設定相對路徑基準 |
RewriteBase /subdir/ |
RewriteMap |
定義對應表 (需主設定檔) |
外部檔案/程式對應 |
四、常用條件變數
| 變數 |
說明 |
%{REQUEST_FILENAME} |
完整檔案系統路徑 |
%{REQUEST_URI} |
請求 URI (含查詢字串前) |
%{QUERY_STRING} |
查詢字串 |
%{HTTP_HOST} |
Host 標頭 |
%{HTTPS} |
on/off (是否 HTTPS) |
%{REMOTE_ADDR} |
客戶端 IP |
五、實戰範例:部落格文章偽靜態
需求
- 原始:
index.php?date=0725
- 目標:
/0725.html、/0726.html
.htaccess 完整規則
RewriteEngine On
RewriteBase /
# 1. 存在的靜態檔案/目錄直接服務 (css, js, images...)
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# 2. 核心偽靜態規則
# ^([0-9]+)\.html$ → 捕獲純數字.html
# 重寫至 index.php?date=$1
RewriteRule ^([0-9]+)\.html$ /index.php?date=$1 [L,QSA]
# 3. 可選:支援任意字元 (不限數字)
# RewriteRule ^(.+)\.html$ /index.php?date=$1 [L,QSA]
PHP 端接收
<?php
// index.php
$date = $_GET['date'] ?? '';
// 驗證格式: 4位數字
if (!preg_match('~^\d{4}$~', $date)) {
http_response_code(404);
exit('Invalid date format');
}
// 查詢資料庫...
echo "顯示 $date 的歷史事件";
?>
六、進階規則範例集
| 需求 |
規則 |
| 強制 HTTPS |
RewriteCond %{HTTPS} off\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] |
| 統一 www / 非 www |
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]\nRewriteRule ^ https://%1%{REQUEST_URI} [L,R=301] |
| 防盜鏈 |
RewriteCond %{HTTP_REFERER} !^$\nRewriteCond %{HTTP_REFERER} !mydomain.com [NC]\nRewriteRule \.(jpg|png|gif)$ - [F] |
| 封鎖惡意 User-Agent |
RewriteCond %{HTTP_USER_AGENT} (bot|spider|crawler) [NC]\nRewriteRule ^ - [F] |
| 維護模式 (排除管理員 IP) |
RewriteCond %{REMOTE_ADDR} !^192\.168\.1\.100$\nRewriteCond %{REQUEST_URI} !/maintenance\.html$\nRewriteRule ^ /maintenance.html [L,R=302] |
七、除錯技巧
🔍 開啟重寫日誌 (Apache 2.4+)
# httpd.conf 或虛擬主機設定
LogLevel alert rewrite:trace3
# 查看日誌
tail -f /var/log/apache2/error.log | grep rewrite
🧪 線上測試工具
八、Nginx 對應設定 (參考)
# Nginx 不用 .htaccess,直接在 server/location 設定
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 特定偽靜態
location ~ ^/([0-9]+)\.html$ {
rewrite ^/([0-9]+)\.html$ /index.php?date=$1 last;
}