6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

heroku+railsでs3にsitemapを置く

Posted at

目的

herokuだとsitemapを置けないためs3に置き、そこから読み込みをgoogleにさせる。

仕様概要

  • sitemapgeneratorでsitemapを作成
  • aws-sdkでs3に保存
  • sitemap専用のルーティングを作ってそれをsearchconsoleに送信
  • robots.txtにもsitemapの場所を記載

aws-sdkでs3に保存

sitemap.rbにsitemapの置き場所を記載

sitemap.rb
SitemapGenerator::Sitemap.default_host = ""
SitemapGenerator::Sitemap.sitemaps_host = "https://s3-ap-northeast-1.amazonaws.com/#{ENV['S3_BUCKET_NAME']}"
SitemapGenerator::Sitemap.adapter = SitemapGenerator::AwsSdkAdapter.new(
  ENV['S3_BUCKET_NAME'],
  aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
  aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
  aws_region: 'ap-northeast-1'
)
SitemapGenerator::Sitemap.create do
  # '/articles/:id' を追加する
  Post.find_each do |post|
    add post_path(post), :lastmod => post.updated_at
  end
end

default_hostでwebsiteのURLを登録。sitemaps_hostでsitemapのURLを登録する。

herokuに環境変数登録

$ heroku config:add S3_BUCKET_NAME=bucket_name
$ heroku config:add AWS_ACCESS_KEY_ID=xxxxxxxxxxxxx
$ heroku config:add AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxx

localはdotenvで環境変数登録

gemのdotenvを入れて環境変数の登録

sitemap専用のルーティングを作る

get '/sitemap' => redirect('https://s3-ap-northeast-1.amazonaws.com/sitename/sitemap.xml.gz')

robots.txtにsitemapの場所を記述

robots.txt
Sitemap: https://sitename/sitemap
6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?