.htaccess 是 Apache 目錄級配置文件,無需重啟主服務即時生效。但需注意:
AllowOverride All 才生效<Directory> 塊檢查 HTTP_REFERER 頭,非授權域名請求靜態資源時返回 403 或替換圖片。
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?partner\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,NC,L]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ /static/images/hotlink-placeholder.jpg [NC,R,L]
關鍵點:佔位圖必須用不同後綴(如 .jpg 規則匹配 .jpeg),避免無限重定向循環。
Order Deny,Allow
Deny from 203.0.113.45
Deny from 198.51.100.0/24
Allow from all
Order Allow,Deny
Allow from 192.168.1.0/24
Allow from 203.0.113.10
Deny from all
Require all granted
Require not ip 203.0.113.45
Require not ip 198.51.100.0/24
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
ErrorDocument 502 /errors/502.html
ErrorDocument 503 /errors/503.html
最佳實踐:
ErrorDocument 404 /error-handler.php?url=%{REQUEST_URI}RewriteEngine On
# 允許管理員 IP 直通
RewriteCond %{REMOTE_ADDR} !^203\.0\.113\.10$
# 排除維護頁面本身避免循環
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
# 排除靜態資源
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|jpeg|gif|ico)$
# 所有請求重定向到維護頁
RewriteRule ^(.*)$ /maintenance.html [R=302,L]
R=302 告訴瀏覽器暫時重定向,利於 SEO 保留排名。
Options -Indexes
效果:無索引文件時返回 403 而非文件列表,防止敏感文件洩露。
# 核心安全頭
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# 隱藏服務器版本
ServerSignature Off
ServerTokens Prod
# 禁止敏感文件訪問
Require all denied
# 限制上傳執行
php_flag engine off
AddHandler cgi-script .php .php5 .phtml
Options -ExecCGI
LogLevel alert rewrite:trace3(僅調試時開啟)curl -I -H "Referer: https://evil.com" https://yoursite/image.jpg