Google sitemap files for Rails projects

后端 未结 6 1974
情深已故
情深已故 2020-12-07 08:13

Is there an easy way to create a sitemaps file for Rails projects? Especially for dynamic sites (such as Stack Overflow for example) there should be a way to dynamically cre

6条回答
  •  执念已碎
    2020-12-07 09:04

    I love John Topley's answer because it is so simple and elegant, without the need for a gem. But it's a bit dated, so I've updated his answer for Rails 4 and Google Webmaster Tools' latest sitemap guidelines.

    config/routes.rb:

    get 'sitemap.xml', :to => 'sitemap#index', :defaults => { :format => 'xml' }
    

    app/controllers/sitemap_controller.rb:

    class SitemapController < ApplicationController
      layout nil
    
      def index
        headers['Content-Type'] = 'application/xml'
        last_post = Post.last
        if stale?(:etag => last_post, :last_modified => last_post.updated_at.utc)
          respond_to do |format|
            format.xml { @posts = Post.all }
          end
        end
      end
    end
    

    app/views/sitemap/index.xml.haml:

    !!! XML
    %urlset{:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9"}
      - for post in @posts
        %url
          %loc #{post_url(post)}/
          %lastmod=post.updated_at.strftime('%Y-%m-%d')
          %changefreq monthly
          %priority 0.5
    

    You can test it by bringing up localhost:3000/sitemap.xml.

提交回复
热议问题