
本文详解如何在 wordpress 环境下,使用 apache 的 mod_rewrite 规则精准阻止 googlebot、bingbot、baiduspider 等主流爬虫访问特定子目录(如 `/tbd_templates/` 和 `/custom_post/`),同时保障网站其余路径正常可访问。
要在不干扰 WordPress 核心重写逻辑的前提下,仅对特定目录实施爬虫屏蔽,关键在于:将规则置于 WordPress 主规则之前,并使用精确匹配的 URL 路径正则表达式,而非全局 .* —— 后者会导致整个站点被误拦。
以下是推荐的 .htaccess 配置方案(插入在 # BEGIN WordPress 之前):
# Block crawlers from specific directories
RewriteCond %{HTTP_USER_AGENT} (googlebot|bingbot|baiduspider) [NC]
RewriteRule ^(tbd_templates|custom_post)(?:$|/) - [F]✅ 说明与要点:
- RewriteCond 检查请求头中的 User-Agent,支持大小写不敏感匹配([NC]);
- RewriteRule 的模式 ^(tbd_templates|custom_post)(?:$|/) 是核心:
- ^ 表示路径开头;
- (tbd_templates|custom_post) 使用括号分组 + 竖线 | 实现多目录“或”匹配;
- (?:$|/) 是非捕获组,确保匹配 /tbd_templates(无尾斜杠)、/tbd_templates/ 或 /tbd_templates/file.html,但不会匹配 /tbd_templates-old/ 或 /mytbd_templates/ 等相似路径,避免误伤;
- [F] 标志等价于 R=403,直接返回 HTTP 403 Forbidden 响应,语义清晰且无需额外 L 标志(F 已隐含终止);
- 无需重复声明 RewriteEngine On —— WordPress 区块中已启用,重复声明虽无害但冗余。
⚠️ 注意事项:
- 该规则仅作用于匹配路径的请求,普通用户、未命中条件的爬虫(如 DuckDuckBot)及 WordPress 其他页面(如 /wp-admin/、/blog/)完全不受影响;
- 若需扩展更多目录,只需在正则中追加,例如:^(tbd_templates|custom_post|private_assets|staging)(?:$|/);
- 修改后务必清除浏览器和 CDN 缓存,并用 curl -A "Googlebot" https://example.com/tbd_templates/ 实际验证响应状态码是否为 403;
- 不建议依赖 User-Agent 屏蔽作为安全手段(可被伪造),它仅适用于 SEO 场景下的临时内容隔离(如开发模板、待上线模块)。
总结:精准路径匹配 + 条件化 User-Agent 判断 + 合理插入位置 = 安全、轻量、可维护的爬虫目录级访问控制。










