在 Apache 的 Virtual Host(虛擬主機)中強制執行 RewriteRule,必須在該 <VirtualHost> 區塊內明確加入 RewriteEngine On,並確保已載入 mod_rewrite 模組。
以下是具體的設定步驟與常見範例:
1. 啟用 mod_rewrite 模組
在套用規則前,請先確認伺服器已載入重寫模組。
- Ubuntu / Debian 系統。執行
sudo a2enmod rewrite並重新啟動 Apache 服務。 - CentOS / RHEL 系統。檢查
/etc/httpd/conf.modules.d/00-base.conf中是否已取消註解LoadModule rewrite_module modules/mod_rewrite.so。
2. 在 Virtual Host 中設定 RewriteRule
Apache 的預設行為是不會將全域的 RewriteEngine 設定自動繼承到個別的 Virtual Host 中,因此每個需要執行重寫的 <VirtualHost> 都必須獨立開啟引擎。
- 強制將 HTTP 轉址至 HTTPS(最常見用法)。在 port 80 的 Virtual Host 中加入以下設定,即可將所有一般連線強制導向加密連線:
apache
<VirtualHost *:80>
ServerName example.com
ServerAlias ://example.com
# 必須在此區塊內開啟 RewriteEngine
RewriteEngine On
# 強制將所有請求透過 301 永久轉址導向 HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
</VirtualHost>
請謹慎使用程式碼。
(註:在 Apache 官方 mod_rewrite 指南 中,若單純做整個網域的 HTTP 轉 HTTPS,其實更推薦直接使用效能較好的 Redirect permanent / https://example.com,但若需要搭配複雜條件判斷,則使用 RewriteRule。)
- 強制統一網域(例如非 www 轉至 www)。在對應的 Virtual Host 區塊內加入條件判斷與規則: [1]
apache
<VirtualHost *:443>
ServerName example.com
ServerAlias ://example.com
DocumentRoot /var/www/html
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://://example.com$1 [R=301,L]
</VirtualHost>
請謹慎使用程式碼。
3. 常見無法生效的排查重點
- 規則位置與目錄權限。若將
RewriteRule寫在<VirtualHost>內的<Directory>區塊中,路徑比對的開頭通常不帶斜線(例如使用^index\.html$而非^/index\.html$)。 - 避免
.htaccess覆蓋。若希望完全由 Virtual Host 強制控管規則,可在<Directory>內設定AllowOverride None。這樣做能防止網站目錄下的.htaccess檔案覆寫或干擾您的設定,同時也能提升 Apache 效能。 - 重新載入設定。修改完成後,務必執行
apachectl configtest檢查語法是否正確,再執行systemctl reload apache2(或httpd)使規則生效。