LoginSignup
0
0

More than 1 year has passed since last update.

sitemap generator + jsonでサイトマップ生成

Posted at

SEO対策でサイトマップをGoogleに登録するため、サイトマップを生成することにしました。
ただ、Next.jsのSSRでサイトを実装していて
インデックスさせたいページの件数が膨大(50万件くらい)だったので、手動で作るのは無理です。

Railsで「sitemap generator」という便利そうなgemがあったので、
こちらを使ってサイトマップを生成してみます。
インデックスさせたいURLは、jsonで下記のような形式で用意しました。

{
  {"id": "123456"}
  {"id": "234567"}
}

まずgemをインストール。

gem install sitemap_generator

sitemap.rbというファイルを作成し、下記の内容を記述します。

sitemap.rb
require 'rubygems'
require 'sitemap_generator'

## 空配列を用意
idList = []

## jsonデータからidの値を読み込む処理を書く(本記事では割愛)
## idListという配列に入れる

SitemapGenerator::Sitemap.default_host = 'http://example.com'
SitemapGenerator::Sitemap.create do
  idList.each do |id|
    add id, :changefreq => 'monthly'
  end
end

これで下記コマンドを実行。

ruby sitemap.rb

+ sitemap.xml.gz                                           2 links /  50 Bytes
Sitemap stats: 2 links / 1 sitemaps / 0m00s

すると、sitemap.xml.gzが/publicに出力されます。
(ここはオプションで出力先を変えることもできるみたいです)

gzは圧縮ファイルなので、解凍して中身を確認。

sitemap.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://example.com/123456</loc>
    <lastmod>2022-06-02T17:37:08+09:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>http://example.com/234567</loc>
    <lastmod>2022-06-02T17:37:08+09:00</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>

無事サイトマップが生成されました。
超膨大(50万件)のjsonデータを読み込ませても、無事生成できました。

しかも、サイトマップはGoogleが1つのサイトマップにつき50,000件までのURLを推奨していますが、このsitemap generatorはデフォルトで50,000件以上になるときは、下記のように分割して生成してくれます。

── public
    └─sitemap.xml.gz  (分割して生成されたsitemap1、2のインデックス用sitemap)
    └─sitemap1.xml.gz 
    └─sitemap2.xml.gz 

インデックス用のサイトマップまで生成してくれるのは助かりますね。
あとはGoogleにサイトマップの送信でsitemap.xml.gzと、解凍した方のsitemap.xmlを送信すればOKです。
(sitemap.xml.gzだけの送信でも良いようですが)

他にもいろいろオプションで設定できそうなので便利ですね!

参考

0
0
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
0
0