Apache 啟動或存取頁面時出現 Internal Server Error,錯誤日誌提示 Invalid command 'RewriteEngine' 或 RewriteRule,主因是 mod_rewrite 模組未載入。本文提供快速啟用步驟與驗證方法。
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator...
More information about this error may be available in the server error log.
錯誤日誌(/var/log/httpd/error_log 或 /var/log/apache2/error.log)典型內容:
[alert] Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration
# CentOS/RHEL/Fedora: /etc/httpd/conf/httpd.conf
# Debian/Ubuntu: /etc/apache2/apache2.conf 或 /etc/apache2/mods-available/rewrite.load
LoadModule rewrite_module modules/mod_rewrite.so
# 找到以下行,移除前方 # 號
#LoadModule rewrite_module modules/mod_rewrite.so
→
LoadModule rewrite_module modules/mod_rewrite.so
a2enmod rewrite
systemctl restart apache2
# 查看已載入模組
httpd -M | grep rewrite
# 或
apache2ctl -M | grep rewrite
# 輸出應包含:
rewrite_module (shared)
AllowOverride All(或至少 AllowOverride FileInfo)。.htaccess:RewriteEngine On
RewriteRule ^test\.html$ /index.html [R=302,L]
https://your-domain/test.html 應重導向至 index.html。| 現象 | 原因 | 對策 |
|---|---|---|
| 重寫規則不生效、無錯誤 | AllowOverride 設為 None | 修改虛擬主機目錄區塊 AllowOverride All |
| 重寫迴圈 (Too many redirects) | 規則邏輯錯誤、缺少 L 旗標、條件不當 | 啟用 RewriteLogLevel 3 偵錯、檢查規則順序 |
| 啟用後 Apache 無法啟動 | mod_rewrite 相依模組未載入、語法錯誤 | 執行 httpd -t / apache2ctl configtest 檢查語法 |
mod_rewrite 是 Apache 最常用也最易被遺漏的模組。部署新環境、遷移專案時,請將 LoadModule rewrite_module modules/mod_rewrite.so 納入標準檢查清單,並善用 a2enmod / httpd -M 驗證,避免上線後遭遇 500 錯誤。