作为 Rails 的初学者,我发现由于其只读限制,在 Heroku 上生成站点地图非常令人畏惧。然而,站点地图是我网站的基础,因为它的成功基于搜索引擎优化。
我尝试过dynamic_sitemaps gem,但很快就删除了它,因为我意识到它没有用于heroku 使用的文档。然后,我使用了 sitemap_generator gem,它涵盖了使用多个 gem 和外部平台(例如 Amazon S3)进行的 heroku 集成。然而问题是,作为一个初学者,我遇到了一些问题,并且发现很难克服它们。
有没有一种解决方案可以让我轻松生成站点地图以获取一致的内容,例如 heroku 平台上的博客文章?我真的很想启动并运行,并且感觉如果我必须使用我已经尝试过的方法,这可能需要一段时间来配置。
Thanks!
我想出了一个小技巧,可以动态生成站点地图文件,但保留它以供以后调用在 Heroku 上.
它非常适合中小型项目,如果您有一个大型项目和数千个不断变化的页面,请考虑使用 S3 来存储站点地图文件。
这些是步骤:
-
use the sitemap_generator
按照此处的指示进行宝石https://github.com/kjvarga/sitemap_generator
-
after bundle
, run rake sitemap:install
,它将创建一个配置/站点地图.rb为您归档
-
编辑配置/站点地图.rb文件看起来像这样
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
- 关于主机名,我建议是
"#{ENV['HOST_PROTOCOL']}://#{ENV['HOST_NAME']}"
(当然还要添加适当的环境变量),以便您可以在不同的环境中更改它。
- 关于压缩,从 false 开始,确保一切正常,如果文件很大,请稍后更改。
-
创建站点地图控制器文件 -应用程序/控制器/sitemap_controller.rb
-
编辑站点地图控制器文件,如下所示
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
- 将索引操作添加到您的routes.rb文件中
resources :sitemap, only: %i[index], constraints: ->(req) { req.format == :xml }
- 重新启动/部署服务器并转到 /sitemap.xml
Enjoy
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)