.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 對不守規則蜘蛛無效,必須用此硬性封鎖。
SetEnvIf User-Agent "^Googlebot" google
Deny from env=google
Deny from ... 規則至 .htaccessRewriteEngine 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/ 目錄,設計友善提示並提供站內導覽。
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 外全擋,並導向指定網址。
RewriteEngine On
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [R=301,L]
R=301 告知搜尋引擎永久移轉,權重傳遞。
AllowOverride All 已在 httpd.conf/vhost 啟用