.htaccess 是 Apache 的分散式設定檔,無需修改主設定檔即可針對特定目錄覆蓋全域設定。支援 Unix/Linux 及所有 Apache 版本,主流海外虛擬主機幾乎全支援(國內部分主機商可能限制)。
# httpd.conf 中需設定
AllowOverride All
# 並載入 rewrite 模組
LoadModule rewrite_module modules/mod_rewrite.so
若需自訂檔名(如 .config),可用 AccessFileName .config 指令。
Windows 不支援直接新建「無檔名、僅副檔名」的檔案,兩種解法:
copy sample.txt .htaccesshtaccess.txt 上傳,再用 FTP 軟體重新命名。ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,NC]
# 僅允許特定 IP
Order Deny,Allow
Deny from all
Allow from 192.168.1.100
Allow from 10.0.0.0/8
# 封鎖特定 IP
Order Allow,Deny
Allow from all
Deny from 203.0.113.50
Options -Indexes
DirectoryIndex index.php index.html index.htm home.php
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
error_log 定位問題。AllowOverride 範圍、RewriteEngine On 是否啟用、路徑是否正確。RewriteLog(舊版)或 LogLevel alert rewrite:trace3(Apache 2.4+)追蹤重寫流程。