技術

【Rails】Railsでsitemap.xmlを作成する

投稿日:

こんにちは

Railsでsaitemap.xmlを作成する方法を紹介します。

sitemapとはサイト内のページリンクをまとめたページのことです。
SEO対策には必要不可欠です。

Railsで作成するには
sitemap_generatorを使います。

先ずはGemfileに追加

gem 'sitemap_generator'

そしてbundle installします。

bundle installが完了したら
configディレクトリ配下にsitemap.rbを作成して
下記を記述します。

Prefectureの部分はご自身のサイトを参考に書いてください。

SitemapGenerator::Sitemap.default_host = "http://www.example.com"

SitemapGenerator::Sitemap.create do
  Prefecture.find_each do |prefecture|
    add prefecture_path(prefecture.friendly_id), :lastmod => prefecture.updated_at
  end
end

これでsitemap.xmlの雛形ができました。
sitemap.xmlの作成には下記のコマンドを叩きます。

rails sitemap:create

そうするとsitemap.xml.gzファイルが作成されます。
出来たものを確認したいところですが
上記ファイルはgzip圧縮されているのでこのままだとファイルが読めませんので
下記のコマンドで解凍します。

gzip -d sitemap.xml.gz

これでsitemap.xmlを作成して確認することができました。

xmlは下記のような形になります。

<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
  xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
  xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
  xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
  xmlns:pagemap="http://www.google.com/schemas/sitemap-pagemap/1.0"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <url>
    <loc>http://www.example.com/hokkaido</loc>
    <lastmod>2019-02-14T16:41:29+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.example.com/aomori</loc>
    <lastmod>2019-02-14T16:41:29+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.example.com/iwate</loc>
    <lastmod>2019-02-14T16:41:29+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.example.com/miyagi</loc>
    <lastmod>2019-02-14T16:41:29+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
.
.
.
urlset>

-技術

執筆者:


comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

関連記事

自分のEvernoteをブログとして公開できる『Postach.io』を使ってみました

こんにちは。たなかです。 自分のEvernoteをブログとして公開できる『Pos …

no image

videoタグとIEの話

以前下記のようなコードでvideoの再生が終了したら別な動画をsrcにセットして …

[Rails]「どのブラウザからのアクセスか」を判別する方法

こんにちは。たなかです。 前回以下のような記事を書きました。   [R …

[Xcode] SDK Version Issue – This app was built with the iOS 12.0 SDK. Starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later.

こんにちは。たなかです。 2019年、ブログ初更新になります。今年もよろしくお願 …

no image

TypescriptでMap使用時にコンパイルエラー

こんにちは 連想配列で重複を省く処理をしたい時にMapを使用することがあります。 …