2013-02-27 14 views
32

私は現在、Express(Node.js)で構築されたアプリケーションで作業しています。異なる環境(開発、生産)で異なるrobots.txtを処理する最も賢い方法を知りたいと思います。Expressで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: /' 

(NB:それはCoffeeScriptのある)

より良いがあるはずです方法。どうしますか?

ありがとうございます。

答えて

46

ミドルウェア機能を使用してください。 robots.txtのはどのセッション、cookieParserなどの前処理されます。この方法:

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

確かに 'app.use( '/ robots.txt'、function(req、res、next){...});'を実行し、 'req.url'チェックを失うことは間違いありません。 – c24w

+0

@ c24wと表現4そうです。 'app.get'も同様に動作します。私は更新します。ありがとう – SystemParadox

+0

ああ、私はそれが新しいAPI機能かもしれないと思った(私はチェックしておくべきだった)。 'app.get'はさらに優れています!:) – c24w

2

okのように見えます。

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のない)

+0

でクローラに利用できるようになり、私はそのような何かをしようと思う、それは私にはもっと優雅に見えます!ありがとうございました! – Vinch

+0

すぐに物事が変わる(Express 4.0)ことを言いたいことがあります。あなたは "ネイティブ" .envが必要です。[process.env.NODE_ENV] :: http://scotch.io/bar-talk/expressjs-4-0-new-features-and-upgrading-from-3-0 – sebilasse

0

app.get 4 Expressは、今、あなたがちょうどそれを使用することができますので、表示された順序で処理されますと

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

ミドルウェアの方法で環境に応じて、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(); 
    } 
    }); 
} 
-2
  1. を作成します。

    User-agent: * 
    Disallow: 
    
  2. public/ディレクトリに追加します。以下の内容で。

あなたrobots.txtが面白いhttp://yoursite.com/robots.txt

関連する問題