萬盛學電腦網

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

Apache .htaccess 進階應用大全:封鎖蜘蛛、防盜鏈、目錄保護、自訂錯誤頁、IP 導向、域名跳轉

前言

.htaccess 是 Apache 目錄級配置檔,無需重啟主機即時生效。本文匯總 6 大實戰場景,附完整指令碼可直接部署。

一、封鎖惡意搜尋引擎蜘蛛 (百度、搜狗等)

SetEnvIfNoCase User-Agent "^Baidu" bad_bot
SetEnvIfNoCase User-Agent "^sogou" bad_bot
SetEnvIfNoCase User-Agent "^Bloghoo" bad_bot
SetEnvIfNoCase User-Agent "^Scooter" bad_bot
Deny from env=bad_bot

原理:識別 User-Agent 設定環境變數,再以 Deny from env= 擋掉。注意:robots.txt 對不守規則蜘蛛無效,必須用此硬性封鎖。

二、封鎖 Googlebot (視需求)

SetEnvIf User-Agent "^Googlebot" google
Deny from env=google

三、依國家 IP 封鎖 (使用線上工具生成)

  1. 訪問 Block Country
  2. 勾選要封鎖國家 → 「Block Now!」→ 複製生成的 Deny from ... 規則至 .htaccess
  3. Apache 回傳 403 給被封 IP

四、防止圖片/檔案盜鏈 (須支援 mod_rewrite)

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !google.com [NC]
RewriteCond %{HTTP_REFERER} !baidu.com [NC]
RewriteRule \.(gif|jpg|jpeg|png|bmp|zip|rar|mp4)$ /static/images/nohotlink.png [R,NC,L]
  • !^$ 允許空 Referer (直接輸入網址)
  • 白名單加入自有域、搜尋引擎、合作站點
  • 盜鏈請求導向預設圖片/頁面

五、保護目錄列表與隱藏特定檔案

# 隱藏所有目錄列表
Options -Indexes

# 進階:顯示列表但隱藏 .php .exe
# Options +Indexes
# IndexOptions -FancyIndexing
# IndexIgnore *.php *.exe

六、自訂錯誤頁面

ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

將錯誤頁面放在 /error/ 目錄,設計友善提示並提供站內導覽。

七、特定 IP 強制導向他站

ErrorDocument 403 https://www.otherdomain.com
Order Deny,Allow
Deny from all
Allow from 124.34.48.165
Allow from 102.54.68.123

除白名單 IP 外全擋,並導向指定網址。

八、舊域名 301 永久導向新域名 (保留路徑)

RewriteEngine On
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [R=301,L]

R=301 告知搜尋引擎永久移轉,權重傳遞。

部署提醒

  • .htaccess 放置於網站根目錄或需生效的子目錄
  • 確認 AllowOverride All 已在 httpd.conf/vhost 啟用
  • 規則修改即時生效,無需重啟 Apache
  • 複雜規則建議先在測試環境驗證正則邏輯
copyright © 萬盛學電腦網 all rights reserved