Rails 项目的 Google 站点地图文件 [英] Google sitemap files for Rails projects
问题描述
是否有一种简单的方法可以为 Rails 项目创建站点地图文件?特别是对于动态站点(例如 Stack Overflow),应该有一种动态创建站点地图文件的方法.使用 Ruby 和/或 Rails 的方法是什么?
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 create a sitemaps file. What is the way to go in Ruby and/or Rails?
你有什么建议?有什么好的宝石吗?
What would you suggest? Is there any good gem out there?
推荐答案
将此路由添加到 config/routes.rb
文件的底部(更具体的路由应在其上方列出):
Add this route towards the bottom of your config/routes.rb
file (more specific routes should be listed above it):
map.sitemap '/sitemap.xml', :controller => 'sitemap'
创建SitemapController
(app/controllers/sitemap_controller):
Create the 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):
—As you can see, this is for a blog, so is using a Post
model. This is the HAML view template (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.
That's it! You can test it by bringing up http://localhost:3000/sitemap.xml (if using Mongrel) in a browser, or perhaps by using cURL.
请注意,如果自上次请求站点地图后没有新帖子,控制器使用 stale?
方法发出 HTTP 304 Not Modified 响应.
Note that the controller uses the stale?
method to issue a HTTP 304 Not Modified response if there are no new posts sinces the sitemap was last requested.
这篇关于Rails 项目的 Google 站点地图文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!