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

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

这就是我现在所拥有的,但我并不相信这个解决scheme,我认为它很肮脏:

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: /' 

(注意:它是CoffeeScript)

应该有更好的办法。 你会怎么做?

谢谢。

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

 app.use(function (req, res, next) { if ('/robots.txt' == req.url) { res.type('text/plain') res.send("User-agent: *\nDisallow: /"); } else { next(); } }); 

随着快递4 app.get现在得到处理的顺序出现,所以你可以使用:

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

看起来像一个好方法。

或者,如果您希望能够将robots.txt作为常规文件进行编辑,并且可能在生产或开发模式下只需要其他文件,则可以使用2个独立的目录,并在启动时激活其中一个。

 if (app.settings.env === 'production') { app.use(express['static'](__dirname + '/production')); } else { app.use(express['static'](__dirname + '/development')); } 

然后在每个robots.txt版本中添加2个目录。

 PROJECT DIR development robots.txt <-- dev version production robots.txt <-- more permissive prod version 

而且您可以在任一目录中继续添加更多的文件,并让您的代码更简单。

(不好意思,这是javascript,不是coffeescript)

使用中间件方式根据环境selectrobots.txt:

 var env = process.env.NODE_ENV || 'development'; if (env === 'development' || env === 'qa') { app.use(function (req, res, next) { if ('/robots.txt' === req.url) { res.type('text/plain'); res.send('User-agent: *\nDisallow: /'); } else { next(); } }); } 
  1. 使用以下内容创buildrobots.txt

     User-agent: * Disallow: 
  2. 将其添加到public/目录。

您的robots.txt将可以在http://yoursite.com/robots.txt上抓取