
本文介绍如何通过 `.htaccess` 文件中的 `rewriterule` 规则,仅对指定子目录(如 `/tbd_templates/` 和 `/custom_post/`)返回 403 禁止访问响应,同时不影响 wordpress 正常路由和其他站点功能。
要在 WordPress 环境中精准限制爬虫(如 Googlebot、Bingbot、Baiduspider)访问特定目录(例如 /tbd_templates/ 和 /custom_post/),不能将泛匹配规则(如 .*)直接放在根目录 .htaccess 中——否则会错误拦截所有请求(包括首页)。正确做法是:将路径限定逻辑写入 RewriteRule 的正则模式中,并置于 WordPress 重写规则之前。
以下是推荐配置(请插入到 # BEGIN WordPress 注释行之前):
# Block specific bots from accessing sensitive directories
RewriteCond %{HTTP_USER_AGENT} (googlebot|bingbot|Baiduspider) [NC]
RewriteRule ^(tbd_templates|custom_post)($|/) - [F]✅ 关键说明:
- ^(tbd_templates|custom_post)($|/): 正则精确匹配 URL 路径(不带域名和协议),支持两种形式:
- /tbd_templates(无尾斜杠)
- /tbd_templates/ 或 /tbd_templates/some-file.php(有尾斜杠或子路径)
- [F] 标志等价于 [R=403],返回标准 HTTP 403 Forbidden 响应,语义清晰且被主流爬虫正确识别。
- RewriteEngine On 无需重复声明——WordPress 区块中已启用,且 Apache 指令按顺序执行,前置规则优先生效。
- 此规则仅作用于符合条件的 User-Agent + 特定路径组合,普通用户、其他爬虫(如 RSS 阅读器)、API 请求等均不受影响。
⚠️ 注意事项:
- 若后续新增受保护目录(如 /staging/),只需扩展正则:^(tbd_templates|custom_post|staging)($|/)
- 确保该规则位于 # BEGIN WordPress 上方;若放错位置,会被 WordPress 的 RewriteRule . /index.php [L] 拦截并绕过防护。
- 测试时建议使用 curl -A "Googlebot" 模拟请求验证效果,例如:
curl -I -A "Googlebot" https://example.com/tbd_templates/ # 应返回 HTTP/1.1 403 Forbidden curl -I -A "Mozilla/5.0" https://example.com/tbd_templates/ # 应返回 HTTP/1.1 200 OK(正常访问)
- 如需屏蔽全部爬虫(不限 UA),可简化条件为 RewriteCond %{HTTP_USER_AGENT} .+,但需谨慎评估 SEO 影响。
综上,该方案兼顾安全性、可维护性与兼容性,是 WordPress 站点中实现细粒度爬虫访问控制的标准实践。










