programing

Rails 프로젝트 용 Google 사이트 맵 파일

nasanasas 2020. 12. 8. 08:16
반응형

Rails 프로젝트 용 Google 사이트 맵 파일


Rails 프로젝트 용 사이트 맵 파일을 만드는 쉬운 방법이 있습니까? 특히 동적 사이트 (예 : Stack Overflow)의 경우 사이트 맵 파일을 동적으로 생성하는 방법이 있어야합니다. Ruby 및 / 또는 Rails로 이동하는 방법은 무엇입니까?

무엇을 제안 하시겠습니까? 거기에 좋은 보석이 있습니까?


config/routes.rb파일 하단에이 경로를 추가 합니다 (더 구체적인 경로가 그 위에 나열되어야 함).

map.sitemap '/sitemap.xml', :controller => 'sitemap'

SitemapController(app / controllers / sitemap_controller)를 만듭니다 .

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.sitemap } # sitemap is a named scope
      end
    end
  end
end

— 보시다시피 이것은 블로그 용이므로 Post모델을 사용하고 있습니다. 다음은 HAML 보기 템플릿 (app / views / sitemap / index.xml.haml)입니다.

- base_url = "http://#{request.host_with_port}"
!!! XML
%urlset{:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9"}
  - for post in @posts
    %url
      %loc #{base_url}#{post.permalink}
      %lastmod=post.last_modified
      %changefreq monthly
      %priority 0.5

그게 다야! 브라우저에서 http : // localhost : 3000 / sitemap.xml (Mongrel을 사용하는 경우)을 가져 오거나 cURL을 사용하여 테스트 할 수 있습니다 .

컨트롤러는 stale?사이트 맵이 마지막으로 요청 된 이후 새 게시물이없는 경우 HTTP 304 Not Modified 응답을 발행하는 방법을 사용합니다 .


이제 rails3의 경우 모든 기능을 갖춘 sitemap_generator gem을 사용하는 것이 좋습니다 .


나는 John Topley의 대답이 너무 간단하고 우아하고 보석이 필요하지 않기 때문에 좋아합니다. 하지만 약간 구식이어서 Rails 4와 Google 웹 마스터 도구의 최신 사이트 맵 가이드 라인에 대한 답변을 업데이트했습니다.

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

localhost : 3000 / sitemap.xml을 불러 와서 테스트 할 수 있습니다.


I would recommend that you check out the sitemap_generator gem. It handles all of these issues for you...and really, who wants to mess around authoring XML?

Here is an example sitemap to show how you use your Rails models and path helpers to generate your sitemap URLs:

# config/sitemap.rb
SitemapGenerator::Sitemap.default_host = "http://www.example.com"
SitemapGenerator::Sitemap.create do
  add '/contact_us'
  Content.find_each do |content|
    add content_path(content), :lastmod => content.updated_at
  end
end

Then you use Rake tasks to refresh as often as you would like. It really is that simple :)


Here is a plugin for creating sitemaps in Ruby on Rails: Ruby on Rails sitemap plugin. It takes care of most of the sitemap logic and generation. The plugin is from my homepage.

Example configuration:

Sitemap::Map.draw do

  # default page size is 50.000 which is the specified maximum at http://sitemaps.org.
  per_page 10

  url root_url, :last_mod => DateTime.now, :change_freq => 'daily', :priority => 1

  new_page!

  Product.all.each do |product|
    url product_url(product), :last_mod => product.updated_at, :change_freq => 'monthly', :priority => 0.8
  end

  new_page!

  autogenerate  :products, :categories,
                :last_mod => :updated_at,
                :change_freq => 'monthly',
                :priority => 0.8

  new_page!

  autogenerate  :users,
                :last_mod => :updated_at,
                :change_freq => lambda { |user| user.very_active? ? 'weekly' : 'monthly' },
                :priority => 0.5

end

Best regards, Lasse


This article explains how a sitemap can be generated.

Basically should should create a controller which finds all pages (eg your Posts) and put in into an XML file. Next you tell Google about the location of the XML file and when your website is updated.

A simple Google rails sitemap query reveals lots of other articles explaining basically the same thing.

참고URL : https://stackoverflow.com/questions/2077266/google-sitemap-files-for-rails-projects

반응형