Help us understand the problem. What is going on with this article?

h2oのmrubyハンドラで`/robots.txt`を出し分ける

More than 1 year has passed since last update.

諸処の事情で、本番とは違うドメインで起動して操作しているWordPressなどがGoogleなどにインデックスされてイヤン、ということもあるでしょう。

いちいちrobotsを切り替えながら操作するのも手間なので、h2oに組み込まれているmrubyで出力をコントロールした。

robots.rb
# デフォルトのDisallowルール
robots = <<EOL
User-Agent: *
Disallow: /
EOL

lambda do |env|
  # /robots.txt以外のリクエストはすぐ処理をh2oに返す
  unless env["PATH_INFO"] == '/robots.txt'
    return [399, {}, []]
  end

  # 任意の条件で、これまた処理をh2oに返す。これはフラグファイル有無での例
  # 環境変数で判断とかでもよい
  if File.exist?('/path/to/flagfile')
    return [399, {}, []]
  end

  # Cookieに`wordpress_logged_in_*` => WordPressにログイン済みっぽいとして扱う
  if env["HTTP_COOKIE"]
    cookies = env["HTTP_COOKIE"].split
    if cookies.select {|a| a.match(/^wordpress_logged_in_/)}.any?
      # カスタマイズしたときのプレビューが出来ないと不便なので、ユーザ定義のrobots.txtを見せる
      return [399, {}, []]
    end
  end

  # これまでの条件にマッチしなければ、デフォルトのDisallowルールを適用
  return [200, {'Content-Type' => 'text/plain;charset=utf-8'}, [robots]]
end

rackベースなのでやりやすい。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした