ruby-on-rails - 目录 : how to catch any route that didn't match route config and redirect to homepage

标签 ruby-on-rails ruby redirect

例如在路由中我有这样的代码:

get "profile/:id" => 'profiles#show', as: :profile

root 'articles#index'

但我怎么能捕捉到这种 url 并重定向到主页:

我需要捕捉任何不存在的路线。为什么我需要这个?通过 SEO 规则。例如,现在如果我输入 url.com/?porn 或 url.com/profile?1&azaza - 我将进入我输入这个难看的 url 的页面。但是我需要重定向到主页,这样任何“黑客”就不会在他们的资源上发布非法链接...

这是真的吗?

最佳答案

您需要处理两种不同的情况

  • 一条错误的道路
  • 错误的资源

对于第一种,您可以在路由末尾添加全局匹配规则。

match '*foo', to: 'articles#index'

然后你应该在你的 Controller 中处理丢失的资源。

例如

def show
  begin
    @article = Article.find(params[:id])
  rescue
    redirect_to root_url
  end
end

当然,如果您有多个 Controller 并且需要在许多地方重复,您应该使用更通用的方法。也许在你的 ApplicationController

上拯救 ActiveRecord::RecordNotFound

关于ruby-on-rails - 目录 : how to catch any route that didn't match route config and redirect to homepage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321457/

相关文章:

cakephp重定向查询

ruby-on-rails - Ruby on Rails 应用程序加速

ruby-on-rails - 纯 Ruby 中的 HTML

ruby-on-rails - 如何在 Rails 中编写对 SEO 友好的路由?

ruby-on-rails - 更快地将数据库从一个 heroku 应用程序传输到另一个应用程序

ruby-on-rails - 具有不止一种特质的工厂女孩​​协会

javascript - Ruby Rails - 带有 AJAX POST 的 Javascript 在本地工作但不能在 Heroku 上工作

ruby - 在 OSX Yosemite(或 Sierra)中安装 compass 时出错

mySQL CAST 和 ASC/DESC

node.js - 无法使用 nginx 隐藏位置的端口