Ruby on RailsでSEOの設定を行うライブラリでmeta-tagsというGemがあります。本記事ではこのGemを使って全ページ共通のSEOの設定や個別ページでの設定をしていきたいと思います。OGP設定もすればSNSでの投稿時の見栄えもよくなります。本番運営するなら必須の設定ですね。
MetaTags
https://github.com/kpumuk/meta-tags
環境はこちらです
1 2 3 |
ruby 2.4.2 rails 5.1.4 vagrant 2.0.2 |
Gemfile
1 |
gem 'meta-tags' |
$ bundle install を実行
Helper
metaデータは直接app/views/layouts/application.html.erbに書いてもいいのですが、ヘルパーメソッドにして呼んだ方が head内がカオスにならなくてすみます。
app/helpers/application_helper.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
module ApplicationHelper def default_meta_tags { title: "title", description: "description", keywords: "rails,seo,meta-tags", #キーワードを「,」で区切る icon: [ { href: image_url('favicon.ico') }, { href: image_url('sample.png'), rel: 'apple-touch-icon', sizes: '180x180', type: 'image/jpg' }, ], noindex: ! Rails.env.production?, # production環境以外はnoindex canonical: request.original_url, # 優先されるurl charset: "UTF-8", # OGPの設定をしておくとfacebook, twitterなどの投稿を見た目よくしてくれます。 og: { title: :title, #上のtitleと同じ値とするなら「:title」とする description: :description, #上のdescriptionと同じ値とするなら「:description」とする type: "website", url: request.original_url, image: image_url("sample_og.png"), site_name: "site name", locale: "ja_JP" }, twitter: { site: '@ツイッターのアカウント名', card: 'summary', image: image_url("sample_twitter.png") # ツイッター専用にイメージを設定する場合 }, fb: { app_id: '***************' #ご自身のfacebookのapplication IDを設定 } } end end |
Views
headに設定すればそのlayoutが適用されている全ページにデフォルトの設定が適用されます。
app/views/layouts/application.html.rb
1 2 3 |
<head> <%= display_meta_tags(default_meta_tags) %> </head> |
あとは上書きしたいページ毎に set_meta_tags を設定して default_meta_tags を上書きします。
ここでは例としてshow.html.erbとしています。変数で渡すこともできます。
app/views/posts/show.html.erb
1 |
<% set_meta_tags title: @post.title, description: @post.content %> |
検索に引っかかって欲しくないページにはnoindex: trueを設定します。
1 |
<% set_meta_tags noindex: true %> |
以上となります!
メタタグは奥が深く、サイトによって適切に設定しいく必要がありそうです。🤔