萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Apache 啟用 URL 重寫 (mod_rewrite) 完整設定教學

Apache URL 重寫依賴 mod_rewrite 模組,需確認模組載入、目錄權限、規則撰寫三大步驟。

1. 確認 mod_rewrite 已編譯/載入

# 查看靜態編譯模組
httpd -l | grep rewrite

# 查看動態載入模組 (DSO)
httpd -M | grep rewrite
# 輸出應含: rewrite_module (shared)

# 若無,檢查 httpd.conf 載入行:
LoadModule rewrite_module modules/mod_rewrite.so
# 或
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so

2. 設定 DocumentRoot 目錄允許覆寫

<Directory "/var/www/html">
    Options FollowSymLinks
    # AllowOverride None  → 註解或改為
    AllowOverride All
    Require all granted
</Directory>
  • AllowOverride All 允許 .htaccess 使用 RewriteRule。
  • 若不使用 .htaccess,可直接在 <VirtualHost> 或 <Directory> 中撰寫 RewriteRule,則不需 AllowOverride。

3. 重啟 Apache 生效

# RHEL/CentOS/Fedora
systemctl restart httpd
# 或
service httpd restart

# Debian/Ubuntu
systemctl restart apache2
# 或
service apache2 restart

# 通用
apachectl graceful

.htaccess 範例:常見重寫規則

RewriteEngine On
RewriteBase /

# 1. 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# 2. 統一 www / non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# 3. 前端框架 History 模式 (Vue/React/Angular)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]

# 4. 目錄補齊斜線 (避免 301)
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R=301,L]

# 5. 靜態檔案快取
RewriteRule \.(css|js|png|jpg|jpeg|gif|ico|woff|woff2)$ - [L]

除錯技巧

  1. 開啟重寫日誌 (Apache 2.4+):
    LogLevel alert rewrite:trace3 (trace1~trace8,生產環境建議 trace2 以下)。
  2. 日誌位置:/var/log/httpd/rewrite_log 或 error_log。
  3. 測試規則:curl -v https://example.com/test 觀察重導向鏈。

效能建議

  • 避免在 .htaccess 大量規則,每次請求皆需讀取解析,改寫入主設定 <Directory> 或 <VirtualHost>。
  • 使用 RewriteMap 處理大量對應 (如舊網址對應新網址)。
  • 善用 [L] (Last)、[END] (Apache 2.4+) 終止後續規則匹配。
copyright © 萬盛學電腦網 all rights reserved