【问题标题】:Redirecting legacy routes presents mapper error with rake重定向遗留路由会导致映射器错误与 rake
【发布时间】:2011-06-04 16:53:11
【问题描述】:

routes.rb:

Myapp::Application.routes.draw do
  root :to => "posts#index"
  match "posts/autocomplete_topic_name", :as => "autocomplete_topic_name"
  match "/new" => "posts#new", :as => :new
  # resources
  resources :topics
  resources :posts
  resources :comments
  # static
  match "/about"   => "pages#about",   :as => :about
  match "/help"    => "pages#help",    :as => :help
  match "/home"    => "home#index",    :as => :home
  # redirects
  match "/tags" => redirect("/topics")
  match "/entries" => redirect("/posts")
  match "/comments" => redirect("/")
end

rake routes 结尾处的错误为:

              tags        /tags(.:format)                          {:to=>#<Proc:0x00000001485d18@/home/basicobject/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/routing/mapper.rb:366 (lambda)>}
            entries        /entries(.:format)                       {:to=>#<Proc:0x0000000133d438@/home/basicobject/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/routing/mapper.rb:366 (lambda)>}
                           /comments(.:format)                      {:to=>#<Proc:0x000000012e8708@/home/basicobject/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/routing/mapper.rb:366 (lambda)>}

我正在尝试将一些旧路由重定向到新路由以获得更好的 SEO。路线如:

/entries/8 需要重定向到 /posts/8 等等。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 redirect routes rake


    【解决方案1】:

    把这个贴在你的application_controller.rb

    rescue_from ActionController::RoutingError do |exception|
      flash[:error] = "Sorry, we were not quite sure where you were trying to go"
      redirect_to root_url
    end
    

    【讨论】:

    • 显示404而不是重定向到root会更好吗? PS:谢谢你的回复。我的下一步是为所有其他路由错误创建一条捕获所有路由。
    • 此问题的作者希望保留旧版 URL。将 404 对 SEO 的影响很小,重定向到 root 也一样。您需要做的是使用新 URL 返回 301。当谷歌遇到 301 时,它会更新它的索引。其他任何事情都会降低您对给定内容的 SEO 排名。
    【解决方案2】:

    您需要保留完整的 url 并将其与任何参数一起传递。在这种情况下,即使是外卡​​匹配也不行,因为您无法将其传递到新路线。

    试试这个

    match "/entries/:post_id" => redirect("/posts/%{post_id}")
    

    这将传递您的参数并抛出正确的 HTTP 错误代码,以便谷歌更新它的索引。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多