79

我目前正在开发一个使用 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: /'

(注意:它是 CoffeeScript)

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

谢谢你。

4

7 回答 7

117

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

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

现在使用 express 4app.get以它出现的顺序进行处理,因此您可以使用它:

app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send("User-agent: *\nDisallow: /");
});
于 2013-11-28T11:36:18.507 回答
20

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

User-agent: *
Disallow: # your rules here

2. 将其添加到public/目录。

3. 如果您的代码中尚未出现,请添加:

app.use(express.static('public'))

robots.txt将可用于任何爬虫,网址为http://yoursite.com/robots.txt

于 2016-11-05T13:39:32.090 回答
2

看起来不错的方式。

另一种方法是,如果您希望能够以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)

于 2013-02-27T19:55:22.420 回答
1

这是我使用的

router.use('/robots.txt', function (req, res, next) {
  res.type('text/plain')
  res.send(
    `User-agent: *
     Disallow: /admin`);
});
于 2021-04-20T09:30:34.427 回答
0

使用中间件方式根据环境选择 robots.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();
    }
  });
}
于 2014-05-31T05:28:35.240 回答
0

这就是我在索引路线上所做的。你可以简单地在你的代码中写下我在下面给出的内容。

router.get('/', (req, res) =>
    res.sendFile(__dirname + '/public/sitemap.xml')
)

router.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/robots.txt')
})
于 2019-07-13T14:29:22.487 回答
0

我使用 robots.txt 作为 Prod 的普通文件,以及其他环境的中间件。

if(isDev || isStaging){
    app.use('/robots.txt', function (req, res) {
        res.type('text/plain');
        res.send("User-agent: *\nDisallow: /");
    });
}
app.use(express.static(path.join(__dirname, 'public')));
于 2020-10-06T14:20:56.333 回答