2019.9.26
検索サイトにインデックスさせたくないページがあったり、まだ公開したくないページなどがある場合、robots.txtで検索サイトのクローラを制御することができます。
Gatsby製のサイトでrobots.txtを配置したかったのでプラグインを試してみました。
gatsby-config.jsに以下の設定項目を追加します。
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-robots-txt',
options: {
host: 'https://www.example.com',
sitemap: 'https://www.example.com/sitemap.xml',
policy: [{ userAgent: '*', allow: '/' }]
}
}
]
};
上記の設定で下記のrobots.txtが作成されます。
User-agent: *
Allow: /
Sitemap: https://www.example.com/sitemap.xml
Host: https://www.example.com
例えばS3にstaging環境を用意している場合などはクロールさせたくありません。そういう場合は環境変数で場合分けすることができます。
gatsby-config.jsにenvを追加してdevelopmentとproductionを追加します。なぜかstagingだとちゃんと動作しませんでした。
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-robots-txt',
options: {
host: 'https://www.example.com',
sitemap: 'https://www.example.com/sitemap.xml',
resolveEnv: () => process.env.GATSBY_ENV,
env: {
development: {
policy: [{ userAgent: '*', disallow: '/' }]
},
production: {
policy: [{ userAgent: '*', allow: '/' }]
}
}
}
}
]
};
コマンドにNODE_ENVを追加します。
"build:development": "NODE_ENV=development gatsby build",
"build:production": "NODE_ENV=production gatsby build,
[追記]上記のGatsbyJSの仕様でgatsby buildはproduction固定になってしまうようになりました。いつか変わったのかなぁ…。
If you run gatsby develop, then you will be in the ‘development’ environment. If you run gatsby build or gatsby serve, then you will be in the ‘production’ environment.
issueを投げてみました。
env property looks not working · Issue #180 · mdreizin/gatsby-plugin-robots-txt · GitHub
代わりにGATSBY_ACTIVE_ENVというプロパティを使えば環境ごとに出し分けできます。
コマンドはこんな感じ。
"build:development": "GATSBY_ACTIVE_ENV=development gatsby build",
"build:production": "GATSBY_ACTIVE_ENV=production gatsby build,
gatsby-config.jsの設定はこのように変えます。
options:
process.env.GATSBY_ACTIVE_ENV === "production"
? {
host: "https://www.example.com",
sitemap: "https://www.example.com/sitemap.xml",
policy: [{ userAgent: "*", allow: "/" }]
}
: {
host: "https://www.example.com",
sitemap: "https://www.example.com/sitemap.xml",
policy: [{ userAgent: "*", disallow: "/" }]
}
これでdevelopment環境とproduction環境のrobots.txtを出し分けすることができます。
まぁググればすぐにわかるんですが、よく使う項目をまとめておきます。
hostrobots.txtが置かれているサイトのホストです。
sitemapsitemap.xmlの場所を記述してクロールを促します。
policyクロールを制御する細かい設定を書くことができます。このページを見ればなんとなく書き方がつかめるかと思います。
だいたい使うのは以下の3つじゃないでしょうか。
userAgent検索サイトのクローラです。Googlebotなどを書きます。全てのクローラに対して設定したい場合は*を書きます。
allowクロールするページを書きます。全てのページをクロールする場合は/と書きます。
disallowクロールさせないページを書きます。全てのページをクロールさせない場合は/と書きます。