技術

【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 を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

関連記事

no image

heroku + node.jsでError R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

こんにちは heroku + node.jsでアプリを作っていて、いざherok …

no image

[Angular]リアクティブフォームのHTML側の記法

Angularのリアクティブフォームではtsファイル側でネストした構成を組むこと …

fullpage.jsでコンテンツを画面幅いっぱいでスクロールさせる。

fullpage.jsとは fullpage.jsは一つのコンテンツを画面いっぱ …

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

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

no image

railsでA server is already running~とでたときの対処法

こんにちは!コーテッグの小山です。 rails使っていて、rails sをすると …