虽然文件可访问,但"Lighthouse无法下载robots.txt文件"

7

我有一个在http://www.schandillia.com运行的NodeJS/NextJS应用程序。该项目具有在http://www.schandillia.com/robots.txt访问的robots.txt文件。目前,该文件只是为测试目的而设置了基本内容。

User-agent: *
Allow: /

然而,当我在我的网站上运行Lighthouse审核时,它会抛出一个“爬取和索引错误”,说它无法下载一个 robots.txt 文件。请注意,该文件可在http://www.schandillia.com/robots.txt找到。
如果您需要查看项目的代码库,请访问https://github.com/amitschandillia/proost robots.txt 文件位于proost/web/static/,但由于我的Nginx配置中的以下内容,在根目录中可以访问:
# ... the rest of your configuration
  location = /robots.txt {
    proxy_pass http://127.0.0.1:3000/static/robots.txt;
  }

完整的配置文件可在 GitHub 上查看:https://github.com/amitschandillia/proost/blob/master/.help_docs/configs/nginx.conf。如有遗漏之处,请提出建议。
1个回答

11
TL;DR: 你的robots.txt已经正常提供,但是由于Lighthouse目前无法与您网站的内容安全策略的connect-src指令一起使用,因为已知限制,该审核无法正确获取它。这个问题现在已经在Chrome 92中得到了解决,并被跟踪为问题#4386

说明: Lighthouse尝试通过从您网站根目录提供的文档运行的脚本来获取robots.txt文件。以下是它用于执行此请求的代码(在lighthouse-core中找到):

const response = await fetch(new URL('/robots.txt', location.href).href);

如果您尝试从您的站点运行此代码,您会注意到会抛出一个“拒绝连接”的错误:

Screenshot of the “Refused to connect” error

这个错误发生是因为浏览器执行了来自你的网站头部的内容安全策略限制(为了方便阅读,这些限制被分成几行)。
content-security-policy:
    default-src 'self';
    script-src 'self' *.google-analytics.com;
    img-src 'self' *.google-analytics.com;
    connect-src 'none';
    style-src 'self' 'unsafe-inline' fonts.googleapis.com;
    font-src 'self' fonts.gstatic.com;
    object-src 'self';
    media-src 'self';
    frame-src 'self'

注意 connect-src 'none'; 部分。根据 CSP规范,这意味着不允许通过脚本接口从已服务的文档中加载任何URL。实际上,任何fetch都会被拒绝。
由于您配置了内容安全策略中间件(来自commit a6aef0e),所以此标头由Next.js应用程序的服务器层明确发送。
import csp from 'helmet-csp';

server.use(csp({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", '*.google-analytics.com'],
    imgSrc: ["'self'", '*.google-analytics.com'],
    connectSrc: ["'none'"],
    styleSrc: ["'self'", "'unsafe-inline'", 'maxcdn.bootstrapcdn.com'], // Remove unsafe-inline for better security
    fontSrc: ["'self'"],
    objectSrc: ["'self'"],
    mediaSrc: ["'self'"],
    frameSrc: ["'self'"]
  }
}));

解决方案/解决方法:要解决审计报告中的问题,您可以选择以下两种方法之一:

  • 等待(或提交)Lighthouse中的修复
  • 使用connect-src 'self'指令,这将导致允许来自您的Next.js应用程序浏览器端的HTTP请求的副作用

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接