.htaccess(分散式配置檔) 是 Apache HTTP Server 的核心特性,允許在目錄層級覆蓋主配置,無需修改 httpd.conf 即可實現 URL 重寫、存取控制、快取策略、錯誤頁面等功能。本文系統梳理核心語法、常見場景與避坑指南。
644# httpd.conf 或虛擬主機配置中AllowOverride All # 允許所有指令;生產建議限制:AllowOverride AuthConfig FileInfo Indexes Limit Require all granted
若 AllowOverride None,.htaccess 將完全失效。虛擬主機商常禁用此功能,使用前請確認。
# httpd.conf AccessFileName .config # 改用 .config 而非 .htaccess
ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html ErrorDocument 403 /errors/403.html
路徑相對於網站根目錄。支援動態腳本:ErrorDocument 404 /error_handler.php?code=404。
RewriteEngine On
RewriteBase /
# 靜態化:/article/123.html → /article.php?id=123
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L,QSA]
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 統一 WWW
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
| 標誌 | 含義 |
|---|---|
| L | Last,停止後續規則處理 |
| R=301 | 永久重導向(SEO 傳遞權重) |
| R=302 | 暫時重導向 |
| QSA | Query String Append,合併查詢字串 |
| NC | No Case,大小寫不敏感 |
| F | Forbidden,回傳 403 |
# 僅允許特定 IP(管理後台) Order Deny,Allow Deny from all Allow from 203.0.113.0/24 198.51.100.50 # 封鎖惡意 IP Order Allow,Deny Allow from all Deny from 192.0.2.100 198.51.100.0/24
Apache 2.4+ 新語法:
Require ip 203.0.113.0/24 Require not ip 192.0.2.100
# 禁止目錄列表(安全預設) Options -Indexes # 或允許特定目錄瀏覽Options +Indexes IndexOptions FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=*
# .htaccess AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd # 絕對路徑,不可在網站根目錄 Require valid-user
產生密碼檔:htpasswd -c /etc/apache2/.htpasswd admin。
ForceType application/octet-stream Header set Content-Disposition "attachment"
ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" ExpiresDefault "access plus 2 days" Header set Cache-Control "public, max-age=31536000, immutable"
php_value upload_max_filesize 50M php_value post_max_size 60M php_value max_execution_time 300 php_flag display_errors Off
copy nul .htaccess 或 type nul > .htaccessNew-Item .htaccess -ItemType File.htaccesshtaccess.txt,上傳後改名| 問題 | 原因 | 解決 |
|---|---|---|
| 500 Internal Server Error | 語法錯誤、模組未載入、指令不被允許 | 檢查 error_log;確認模組載入;縮小 AllowOverride 範圍測試 |
| 重寫規則不生效 | RewriteEngine Off、路徑錯誤、衝突規則 | 加上 RewriteBase;用 RewriteLog 除錯(僅 2.4-) |
| 無限重導向迴圈 | 規則互相觸發 | 善用 L 標誌;加入 RewriteCond 排除目標路徑 |
| 子目錄規則不生效 | 父目錄 AllowOverride None | 檢查父目錄配置 |
| 密碼保護彈窗不出現 | AuthUserFile 路徑錯誤、權限不足 | 使用絕對路徑;確認 Apache 讀取權限 |
httpd.conf 僅啟動讀取一次,效能優於 .htaccessNginx 不支援 .htaccess。所有規則需寫在 nginx.conf 或站點配置中。常見轉換:
rewrite 指令deny/allowerror_pageexpires/add_header.htaccess 是 Apache 獨有的強大工具,掌握重寫、存取控制、快取、錯誤處理四大核心場景,即可應對 90% 的目錄級配置需求。記住:開發靈活、上線遷移、效能優先,才是專業運維態度。