こんにちは
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>







