Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Apache 啟用 .htaccess 偽靜態完整設定:LoadModule rewrite 與 AllowOverride All

編輯:Linux 教學

虛擬主機預設常關閉 .htaccess,導致偽靜態、301 轉向、404 自訂失效。本文說明在擁有權限(VPS/專屬伺服器/本地環境)下的啟用步驟。

一、確認載入 rewrite 模組

編輯 httpd.conf(通常在 /etc/httpd/conf/ 或 /usr/local/apache/conf/),搜尋:

LoadModule rewrite_module modules/mod_rewrite.so

確認行首無 # 號。若有,移除並重啟 Apache。

二、允許 .htaccess 覆蓋設定

在 httpd.conf 找到網站根目錄對應的 <Directory> 區塊:

<Directory "/var/www/html">
    Options FollowSymLinks
    AllowOverride None   # 改為 All
</Directory>

修改為:

AllowOverride All

三、重啟 Apache 生效

# CentOS 6 / SysV
service httpd restart
/etc/init.d/httpd restart

# CentOS 7/8 / systemd
systemctl restart httpd

# Ubuntu/Debian
systemctl restart apache2

四、驗證 .htaccess 生效

於網站根目錄建立 .htaccess:

RewriteEngine On
RewriteRule ^test\.html$ index.php [L]

瀏覽 https://domain/test.html 若正確導向 index.php 即生效。

五、常見 .htaccess 用途

  • 偽靜態 URL 重寫
  • 301 永久轉向
  • 自訂 404/500 錯誤頁
  • 防盜鏈、IP 黑白名單、目錄瀏覽控制
  • 強制 HTTPS、Gzip 壓縮、快取標頭

注意

  • 虛擬主機通常無權修改 httpd.conf,需請求業者協助或升級方案。
  • AllowOverride All 會讓 Apache 掃描每層目錄的 .htaccess,略微影響效能;高流量站建議將規則直接寫入 httpd.conf 的 <Directory> 或 <VirtualHost>。

完成上述設定,Apache 即可完整支援 .htaccess 所有功能。

Copyright © Windows教程網 All Rights Reserved