Overview
Generate sitemap indexes and child sitemaps from explicit Ruby definitions. It is for Ruby and Rails developers who keep sitemap inclusion rules in application code. Storage, URL selection, scheduling and serving remain application responsibilities.
Installation
Ruby 4.0 or newer. Active Support 8 is required; Rails integration is optional. Rails tasks and the install generator target Rails 8.
gem install indexmap
For a Bundler application, add gem "indexmap" to its Gemfile and run bundle install.
Use require: false for Rails applications to keep the generation or crawl stack out of ordinary web and job boot.
Quick start
require "indexmap"
Indexmap.configure do |config|
config.base_url = "https://example.com"
config.storage = Indexmap::Storage::Filesystem.new(
path: "public", public_url: config.base_url
)
config.sections = [
Indexmap::Section.new(
filename: "sitemap-pages.xml",
entries: [Indexmap::Entry.new(loc: "https://example.com/")]
)
]
end
Indexmap.create
Run from your project directory. This writes public/sitemap.xml and public/sitemap-pages.xml. The first file references the second; the second contains the home-page URL.
Usage
Rails Usage
Run the install generator after adding the gem:
bin/rails generate indexmap:install
The generator creates config/initializers/indexmap.rb using Rails’ native
load hook and adds require "indexmap/tasks" to the application’s Rakefile.
Normal web and worker boot does not load Indexmap. Rakefiles run only for tasks,
so task discovery needs no argument parsing.
Customize the generated initializer:
ActiveSupport.on_load(:indexmap) do
Indexmap.configure do |config|
config.base_url = -> { ENV.fetch("BASE_URL", "https://example.com") }
config.storage = -> do
Indexmap::Storage::Filesystem.new(
path: Rails.public_path, public_url: config.base_url
)
end
config.sections = -> { Sitemap.sections }
end
end
Keep storage, route helpers and source queries inside their callables. Passing
public_url: config.base_url while constructing an adapter outside a callable
resolves the origin immediately, before routes or later initializers may exist.
Moving that eager expression to after_initialize does not make route helpers
available reliably. The storage callable resolves once per operation.
Runtime callers only require the gem and invoke the operation:
require "indexmap"
Indexmap::TaskRunner.new.create
The load hook applies configuration whether the gem loads before or after the initializer. No host module, mutex, explicit apply call, or custom task loader is needed. Existing manually configured Ruby callers remain supported.
Then run:
bin/rails indexmap:sitemap:create
bin/rails indexmap:sitemap:validate
Creation already validates. indexmap:sitemap:format optionally pretty-prints
legacy XML after publication; it rejects atomic outputs.
indexmap:sitemap:create is the main task. It stages partitioned XML on temporary
disk, validates the complete result, then publishes to configured storage.
Generation and validation failures leave published files untouched. Legacy
publication remains sequential; enable atomic mode for immutable children and
revision-checked root activation. See dynamic sitemaps.
Background Generation
Keep the refresh job and its scheduling in the host application. Indexmap does
not select a queue adapter, run workers, or deduplicate jobs. Require the gem
inside the job. Use Indexmap::TaskRunner.new.create for the
rake task’s complete lifecycle, including after_create callbacks and IndexNow
key-file handling; Indexmap.create only generates the selected output.
GoodJob
With GoodJob 4.22.1 or newer, use its public labelled concurrency rules:
class SitemapRefreshJob < ApplicationJob
include GoodJob::ActiveJobExtensions::Concurrency
good_job_concurrency_rule(
perform_limit: 1,
label: "sitemap-refresh",
apply_label: true
)
good_job_concurrency_rule(
total_limit: 1,
label: -> { "sitemap-refresh:#{arguments.first}" },
apply_label: true
)
def perform(_version)
require "indexmap"
Indexmap::TaskRunner.new.create
end
end
Enqueue with a release identifier: SitemapRefreshJob.perform_later(version).
The version label limits unfinished work for that release; the shared label
limits generation across releases to one execution at a time. A newer release
can enqueue while an older refresh is unfinished. A repeat enqueue is allowed
after completion: these controls do not provide permanent once-per-release
tracking. Use perform_later; direct perform_now calls bypass GoodJob’s limits.
See GoodJob concurrency controls.
Solid Queue
With Solid Queue 1.7 or newer, serialize writes to the shared sitemap output:
class SitemapRefreshJob < ApplicationJob
limits_concurrency to: 1, key: "sitemap-refresh",
duration: 30.minutes, on_conflict: :block
def perform(_version)
require "indexmap"
Indexmap::TaskRunner.new.create
end
end
Choose a duration longer than the expected generation time. :block retains
every refresh and runs them serially; it does not suppress duplicate enqueues.
Using on_conflict: :discard coalesces conflicting requests, including requests
for newer releases when the key is shared. A version-based key such as
->(version) { "sitemap-refresh:#{version}" } scopes conflicts to that release,
but permits different releases to write concurrently. Select that tradeoff
explicitly; it is not equivalent to GoodJob’s two rules above. Direct
perform_now calls bypass queue coordination.
See Solid Queue concurrency controls.
Triggering Refreshes
Enqueue from one release task, a recurring schedule, or application startup.
Rails’ after_initialize hook can enqueue from a worker application without
depending on a backend’s worker callbacks:
Rails.application.config.after_initialize do
if Rails.env.production? && ENV["PROCESS_ROLE"] == "worker"
SitemapRefreshJob.perform_later(ENV.fetch("RELEASE_VERSION")) do |job|
raise job.enqueue_error if job.enqueue_error
end
end
end
PROCESS_ROLE and RELEASE_VERSION are application-defined environment values.
Configure them in the deployment, with the worker role flag limited to worker
processes. after_initialize runs for every Rails process, including commands;
it indicates application initialization, not worker readiness. Complete database
preparation before starting workers. Suppressed enqueues are expected; report
actual enqueue errors. Avoid scheduling the same refresh from both startup and
a release task.
Use storage shared by all serving containers, such as object storage through the Active Storage adapter. A job container’s local filesystem is not shared with web containers unless the deployment mounts the same persistent storage.
Operating Practices And Current Limits
Generate database-backed content after database preparation, through one host-owned refresh job. Load the existing configuration inside that job and query eligible records when it runs. Pass release or output identifiers rather than relations, URL inventories, or credentials. Keep queue selection, recurring schedules, and any application authorization context in the host.
Use a shared concurrency key or label for jobs writing the same destination, across releases. Prefer blocking or rescheduling conflicts to discarding a newer refresh. Backend controls do not protect manual rake invocations, and Solid Queue’s concurrency duration can expire before an unusually long job finishes. Avoid concurrent writers through all entrypoints in legacy mode: an interrupted sequential publication can leave mixed generations. Opt-in atomic mode checks root revisions under a storage lock and retains previous generations. See the publication and retention contract.
Keep generation and search-engine submission separate. A refresh retry should
not automatically resend successful IndexNow batches. Make after_create
callbacks safe to repeat: they run after publication, and a callback failure does
not roll published files back. Validate the deployed sitemap and preview IndexNow
selection before submitting. See selection and attempt reports.
Batch source queries with native Rails APIs and select the fields needed for
URLs and dates. Supply meaningful content dates; do not use the refresh time as
lastmod. Each sitemap must stay within 50,000 entries and 52,428,800 uncompressed
bytes. Index mode partitions automatically; single-file mode rejects an output
that needs splitting. Measure the complete refresh before adding parallel jobs or
caches. Supply lazy sources to benefit from incremental generation and validation;
app-owned arrays and explicit inventory-returning APIs still retain their data.
Generation uses the same synchronous entrypoints with GoodJob and Solid Queue; the examples above describe their different concurrency behavior. Verify the host’s actual adapter, workers, shared storage, failure reporting, and intended system context in integration tests. Gem tests alone do not establish those deployment guarantees.
Dynamic Robots
Indexmap can serve /robots.txt from configuration without querying content or
reading sitemap storage. Crawling defaults to disabled. Inside the generated
Indexmap.configure block, configure the site’s policy:
config.robots.indexable = -> { Rails.env.production? && ENV["PUBLIC_INDEXING"] == "1" }
config.robots.groups = [
{user_agent: "*", allow: ["/"], disallow: ["/admin/", "/search"]}
]
The sitemap URL defaults to base_url plus index_filename. Override it with
config.robots.sitemaps = ["https://example.com/sitemap.xml"] when needed.
Groups and sitemap lists also accept callables. Keep them configuration-only;
do not query models in these callables.
In the application’s config/routes.rb, load and mount the endpoint explicitly:
require "indexmap/robots_controller"
Rails.application.routes.draw do
get "/robots.txt", to: Indexmap::RobotsController.action(:show)
end
Keep the load hook in an initializer. Remove public/robots.txt so it cannot
shadow the route.
The controller supports GET, HEAD, and conditional requests, uses a one-hour
public cache, and does not inherit application authentication or browser gates.
Set PUBLIC_INDEXING only for the intended public deployment; production-mode
previews should remain disabled. Robots rules do not replace authorization or
page-level indexing directives.
Default Index Mode
This is the default behavior. indexmap writes:
-
sitemap.xmlas a sitemap index - one or more child sitemap files from
config.sections
Section entries can be enumerables. Indexmap consumes each section once and
calculates its index lastmod in that same pass. For database sources, return a
fresh enumerable from the configured sections callable on every generation:
config.sections = -> do
entries = PublicPage.indexable.find_each.lazy.map do |page|
Indexmap::Entry.new(loc: page.canonical_url, lastmod: page.updated_at)
end
[Indexmap::Section.new(filename: "sitemap-pages.xml", entries: entries)]
end
PublicPage, its eligibility scope, and canonical URL method are host-app
examples. Keep queries and routing decisions in the host. Generation stages
bounded partitions and validates incrementally, using temporary disk for global
duplicate checks. See memory and disk limits.
Single-File Mode
For sites that only want one sitemap.xml file:
Indexmap.configure do |config|
config.base_url = -> { "https://example.com" }
config.storage = Indexmap::Storage::Filesystem.new(path: Rails.public_path, public_url: config.base_url)
config.format = :single_file
config.entries = -> do
[
Indexmap::Entry.new(loc: "https://example.com/"),
Indexmap::Entry.new(loc: "https://example.com/about", lastmod: Date.new(2026, 4, 21))
]
end
end
In :single_file mode, indexmap writes a urlset directly to sitemap.xml and reads entries from config.entries instead of config.sections.
Named Outputs
Most apps only need the default output. Use named outputs when one part of the sitemap must be generated separately, for example when static pages can be generated during deploy but database-heavy pages should refresh later. Named outputs write through the same configured storage as the default output.
Indexmap.configure do |config|
config.base_url = -> { "https://example.com" }
config.storage = Indexmap::Storage::Filesystem.new(path: Rails.root.join("storage/sitemaps"), public_url: config.base_url)
config.sections = -> { Sitemap.sections }
config.output :insights_data do |output|
output.format = :single_file
output.index_filename = "sitemap-insights-data.xml"
output.entries = -> { Sitemap.insights_data_entries }
end
end
Generate the default output:
Indexmap.create
Generate only the named output:
Indexmap.create(:insights_data)
Named outputs inherit base_url and format from the main configuration unless
you override them. Storage is configured once and shared by every output.
Indexmap.create stages XML, validates it, then publishes the selected output.
Only Indexmap::TaskRunner#create (also used by the create task) handles the
IndexNow key file and after_create callbacks. Formatting is a separate optional
operation for legacy outputs; atomic outputs must be regenerated.
Storage
Every indexmap operation reads and writes through config.storage. The storage
object is the source of truth for generation, validation, parsing, Google
submission, IndexNow submission, and IndexNow verification files.
The filesystem adapter stores files in a directory and exposes public URLs from the same filenames:
Indexmap.configure do |config|
config.base_url = "https://example.com"
config.storage = Indexmap::Storage::Filesystem.new(
path: Rails.public_path,
public_url: "https://example.com"
)
end
Rails apps that store sitemap files in Active Storage can use the optional
adapter. indexmap does not depend on activestorage; this adapter only uses
the model and attachment object you pass in.
Indexmap.configure do |config|
config.base_url = "https://example.com"
config.storage = Indexmap::Storage::ActiveStorage.new(
model: SitemapArtifact,
filename_column: :filename,
attachment: :file,
public_url: "https://example.com"
)
end
Custom storage backends can implement the same small interface:
storage.write(filename, body, content_type:)
storage.read(filename)
storage.exist?(filename)
storage.list(prefix:, suffix:)
storage.delete(filename)
storage.public_url(filename)
Atomic publication, pruning, and streamed HTTP delivery require additional
capabilities. See the storage contract for signatures,
return values, and adapter requirements. Each operation instance resolves a
storage callable once and shares the adapter with its collaborators. Create a
fresh runner/pinger after changing destinations or tenant context. Direct reads
of config.storage still resolve the callable; construct an adapter once in the
host loader when its settings are fixed for the process.
Deferred Dynamic Sections
Use after_create when indexmap:sitemap:create should publish the default
sitemap first, then schedule slower dynamic sections for the background. The
callback runs only after the default output has been validated and published
and configured IndexNow key-file handling has succeeded. It also runs for
Indexmap::TaskRunner#create; Indexmap.create does not run callbacks.
Indexmap.configure do |config|
config.base_url = -> { "https://example.com" }
config.storage = Indexmap::Storage::Filesystem.new(path: Rails.root.join("storage/sitemaps"), public_url: config.base_url)
config.sections = -> { Sitemap.sections }
config.output :insights_data do |output|
output.format = :single_file
output.index_filename = "sitemap-insights-data.xml"
output.entries = -> { Sitemap.insights_data_entries }
end
config.after_create do
Insights::SitemapRefreshJob.perform_later
end
end
Then the job can stay small:
class Insights::SitemapRefreshJob < ApplicationJob
def perform
require "indexmap"
Indexmap.create(:insights_data)
end
end
The default output and named output are independent roots. List both public
root URLs in config.robots.sitemaps (or the static robots file) and submit each
separately if needed; named outputs are not automatically linked into the default
index. Publish the named output before advertising its URL. A deferred job can
fail after the default root is published, so monitor it separately.
Validation And Parsing
indexmap also includes small utilities for working with generated sitemap files:
parser = Indexmap::Parser.new(source: "sitemap.xml")
parser.paths
# => ["/", "/about", "/articles/example"]
Indexmap::Validator.new.validate!
The built-in validator checks for:
- missing sitemap files
- malformed sitemap XML
- empty sitemap files
- missing or duplicate child sitemap references
- duplicate sitemap URLs
- parameterized URLs in sitemap entries
- fragment URLs in sitemap entries
- non-HTTP or relative URLs
- URLs outside the configured
base_url - invalid
lastmodvalues
Search Engine Ping
indexmap can ping Google Search Console and IndexNow after sitemap generation.
For known page updates or removals, pass entries: directly to
Indexmap::Pinger::IndexNow#ping; see direct change submission.
See Search engine ping for Google credential
setup, Search Console property configuration, and IndexNow key provisioning.
For Rails apps with sitemaps outside public/, see
serving an IndexNow key from public/.
Key discovery searches the configured sitemap storage, so an existing public
key file needs explicit configuration in that setup.
Available rake tasks:
bin/rails indexmap:sitemap:validate
bin/rails indexmap:google:ping
bin/rails indexmap:index_now:ping
bin/rails indexmap:index_now:write_key
bin/rails indexmap:ping
If Google credentials are blank, indexmap:google:ping skips Google
submission. If neither a configured IndexNow key nor a valid key file is
present, indexmap:index_now:ping skips IndexNow submission.
Technical details
Generation stages XML and validates it before publication. Legacy publication writes files sequentially; it does not guarantee atomic replacement of a complete generation. Opt-in atomic mode requires storage capabilities described below. Indexmap.create generates the selected output; Indexmap::TaskRunner#create also handles IndexNow key files and after_create callbacks. A callback failure does not roll back published files.
Project resources
The repository retains implementation contracts and contributor references: architecture, domain terms, deployment, storage, dynamic sitemaps and search-engine submission. The usage guide on this page is the canonical public documentation.
- GitHub repository
- RubyGems package
- Changelog
- Issues
- Upgrade notes
- MIT license
-
Development and contributing: fork, create a branch and run
bundle exec rake verifybefore opening a pull request.
About Ethos Link
Ethos Link is a software company founded by Paulo Fidalgo. We publish these Ruby tools alongside our business products.
- Reviato: private customer feedback and public review analysis.
- Nuntio: prepare, review and schedule social posts.
- EthosPlaces: find places, opening hours and contact details.