虛擬主機預設常關閉 .htaccess,導致偽靜態、301 轉向、404 自訂失效。本文說明在擁有權限(VPS/專屬伺服器/本地環境)下的啟用步驟。
編輯 httpd.conf(通常在 /etc/httpd/conf/ 或 /usr/local/apache/conf/),搜尋:
LoadModule rewrite_module modules/mod_rewrite.so
確認行首無 # 號。若有,移除並重啟 Apache。
在 httpd.conf 找到網站根目錄對應的 <Directory> 區塊:
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride None # 改為 All
</Directory>
修改為:
AllowOverride All
# CentOS 6 / SysV service httpd restart /etc/init.d/httpd restart # CentOS 7/8 / systemd systemctl restart httpd # Ubuntu/Debian systemctl restart apache2
於網站根目錄建立 .htaccess:
RewriteEngine On RewriteRule ^test\.html$ index.php [L]
瀏覽 https://domain/test.html 若正確導向 index.php 即生效。
AllowOverride All 會讓 Apache 掃描每層目錄的 .htaccess,略微影響效能;高流量站建議將規則直接寫入 httpd.conf 的 <Directory> 或 <VirtualHost>。完成上述設定,Apache 即可完整支援 .htaccess 所有功能。