在Express中处理robots.txt最聪明的方法是什么?

Vin*_*nch 61 robots.txt node.js express

我目前正在开发一个使用Express(Node.js)构建的应用程序,我想知道处理不同环境(开发,生产)的不同robots.txt的最聪明方法是什么.

这就是我现在所拥有的,但我不相信解决方案,我认为它很脏:

app.get '/robots.txt', (req, res) ->
  res.set 'Content-Type', 'text/plain'
  if app.settings.env == 'production'
    res.send 'User-agent: *\nDisallow: /signin\nDisallow: /signup\nDisallow: /signout\nSitemap: /sitemap.xml'
  else
    res.send 'User-agent: *\nDisallow: /'
Run Code Online (Sandbox Code Playgroud)

(注意:这是CoffeeScript)

应该有更好的方法.你会怎么做?

谢谢.

Sys*_*dox 93

使用中间件功能.这样robots.txt将在任何会话,cookieParser等之前处理:

app.use('/robots.txt', function (req, res, next) {
    res.type('text/plain')
    res.send("User-agent: *\nDisallow: /");
});
Run Code Online (Sandbox Code Playgroud)

现在快递4 app.get按照它出现的顺序处理,所以你可以使用它:

app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send("User-agent: *\nDisallow: /");
});
Run Code Online (Sandbox Code Playgroud)

  • 这里的第二种方法更好,因为OP用于表达<4.然后添加中间件意味着所有请求都通过此robots.txt检查. (3认同)

小智 6

  1. robots.txt使用以下内容创建:

    User-agent: *
    Disallow:
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将其添加到public/目录。

robots.txt可以在以下位置对抓取工具进行访问http://yoursite.com/robots.txt

  • Express不会自动从`/ public`提供静态文件吗?我认为您需要对其进行配置。因此答案是不完整的。 (5认同)