网站之robots.txt用法及nginx下如何配置

robots.txt网站 SEO 和爬虫访问控制的关键配置文件之一,通常由 Nginx 直接静态返回,不经过后端,提高性能和安全性。


1.基础生产配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
server {
listen 80;
server_name www.example.com;

root /data/www/html;

# robots.txt 静态文件配置
location = /robots.txt {
alias /data/www/html/robots.txt;
add_header Content-Type "text/plain";
expires 1h;
access_log off;
}

# 静态资源缓存策略
location ~* \.(css|js|jpg|jpeg|png|gif|ico|webp|svg)$ {
expires 30d;
add_header Cache-Control "public";
}

# 默认页面
location / {
try_files $uri $uri/ /index.html;
}
}

2.robots.txt文件内容示例

2.1通用版(允许所有爬虫)

1
2
3
User-agent: *
Disallow:
Sitemap: https://www.example.com/sitemap.xml

2.2限制内部环境或测试环境(禁止爬虫)

1
2
User-agent: *
Disallow: /

2.3部分目录禁止爬取(如后台、日志)

1
2
3
4
5
6
User-agent: *
Disallow: /admin/
Disallow: /api/private/
Disallow: /logs/
Allow: /public/
Sitemap: https://www.example.com/sitemap.xml

3.Nginx配置要点解释

项目 说明 推荐值
location = /robots.txt 精确匹配,防止被动态规则覆盖 ✅ 必须用 =
alias 指定 robots.txt 的真实路径 root 更灵活
add_header Content-Type 明确返回纯文本类型 text/plain
expires 可缓存 1 小时 避免频繁请求
access_log off 关闭访问日志 降低磁盘 IO
try_files 防止路径穿透 /index.html 兜底

4.架构流转图

sequenceDiagram
    participant C as Client (Crawler)
    participant N as Nginx
    participant F as robots.txt File

    C->>N: GET /robots.txt
    N->>F: 读取文件内容
    N-->>C: 返回 200 + text/plain
    C->>C: 解析 Disallow / Allow 规则

5.生产实战建议

  1. 不同环境配置不同 robots.txt

    • 测试环境Disallow: /
    • 正式环境:开放爬取并加上 Sitemap
      可在 Nginx 中通过变量或环境变量区分。
  2. 利用 CDN 缓存

    • 可设置 Cache-Control: public, max-age=3600
      减少源站压力。
  3. 防止动态服务覆盖

    • 确保 /robots.txt 匹配在所有 location 之前。
  4. 版本控制

    • 建议 robots.txt 与代码仓库同步管理。