萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Apache .htaccess 實戰五大核心技巧:防盜鏈、IP封禁、錯誤頁、維護模式、目錄保護

前言:.htaccess 權力與責任

.htaccess 是 Apache 目錄級配置文件,無需重啟主服務即時生效。但需注意:

  • 主配置 AllowOverride All 才生效
  • 性能影響:每次請求遞歸讀取父目錄 .htaccess
  • 生產環境建議將常用規則遷移至主配置 <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]

進階:返回警告圖片而非 403

RewriteRule \.(jpg|jpeg|png|gif|webp)$ /static/images/hotlink-placeholder.jpg [NC,R,L]

關鍵點:佔位圖必須用不同後綴(如 .jpg 規則匹配 .jpeg),避免無限重定向循環。

技巧二:IP 訪問控制

封禁單個/多個 IP

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

最佳實踐:

  • 錯誤頁使用絕對路徑或相對 DocumentRoot 路徑
  • 404 頁保留站點導航、搜索框、網站地圖鏈接
  • 50x 頁顯示預計恢復時間、客服聯繫方式
  • 可指向動態腳本: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
  • 常見陷阱:規則順序、正則貪婪匹配、編碼問題、緩存干擾
copyright © 萬盛學電腦網 all rights reserved