What should I be using for sitemap generation for rails on heroku?

后端 未结 3 1627
甜味超标
甜味超标 2021-01-24 03:04

As a beginner to rails, I\'m finding the generation of sitemaps on Heroku to be extremely daunting due to its read-only limitations. However, a sitemap is fundamental to my webs

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 03:30

    I figured out a small trick that makes it possible to dynamically generate the sitemap file but persist it for later calls on Heroku.

    It works great for small\medium size projects, if you have a big\huge project and thousand of pages that changes endlessly , please consider using S3 to store the sitemap file.

    Those are the steps:

    1. use the sitemap_generator gem as instructed here https://github.com/kjvarga/sitemap_generator

    2. after bundle, run rake sitemap:install, it will create a config/sitemap.rb file for you

    3. edit the config/sitemap.rb file to look like this

      SitemapGenerator::Sitemap.default_host = [your host name goes here]

      SitemapGenerator::Sitemap.public_path = File.join(Rails.root, 'tmp').to_s

      SitemapGenerator::Sitemap.compress = false

      SitemapGenerator::Sitemap.create do

      [all your site pages add commands goes here]

      end

    • regarding the host name, I suggest it to be "#{ENV['HOST_PROTOCOL']}://#{ENV['HOST_NAME']}" (and of course add the appropriate environment variables) so you could change it on different environments.
    • regarding compress, start with false, make sure all is working great for you and change it later if it is a big file.
    1. create your sitemap controller file - app/controllers/sitemap_controller.rb

    2. Edit the sitemap controller file to look like this

    require 'rake'

    class SitemapController < ApplicationController
      def index
        file_name = File.join(Rails.root, 'tmp', 'sitemap.xml').to_s
        
        unless File.exist?(file_name)
          Rails.application.load_tasks
          Rake::Task['sitemap:refresh:no_ping'].invoke
        end
        
        # it's better to be safe than sorry 
        if File.exist?(file_name)
          respond_to do |format|
            format.xml { render file: file_name }
          end
        else
          render file: 'public/404.html', status: :not_found, layout: false
        end
      end
    end
    
    1. Add the index action to your routes.rb file

    resources :sitemap, only: %i[index], constraints: ->(req) { req.format == :xml }

    1. restart/deploy you server and go to /sitemap.xml

    Enjoy

提交回复
热议问题