RoR:如何捕获任何与路由配置不匹配的路由并重定向到主页

时间:2021-06-12 19:31:18

For example in routes i have such code:

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

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

root 'articles#index'

but how could i catch such kind of url and redirect to home:

但我怎么能抓到这样的网址并重定向到家:

i need to catch any non existing route. Why i need this? via SEO rules. Becouse for example now if i enter url.com/?porn or url.com/profile?1&azaza - i will be on page where i entered this ugly url. But i need to redirect to home, so that any "hacker" didn't not post illegal link's on they resources...

我需要抓住任何不存在的路线。为什么我需要这个?通过SEO规则。例如,如果我输入url.com/?porn或url.com/profile?1&azaza - 我将进入我输入这个丑陋网址的页面。但我需要重定向到家,所以任何“黑客”都不会在他们的资源上发布非法链接......

is it real to do?

是真的吗?

1 个解决方案

#1


0  

There are two different cases you need to take care of

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

  • a wrong path
  • 错误的道路

  • a wrong resource
  • 错误的资源

For the first one, you can add a global match rule at the end of the routes.

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

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

Then you should handle the missing resources in your controllers.

然后,您应该处理控制器中缺少的资源。

eg

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

Of course if you have multiple controllers and need to repeat that in many places you should use a more general approach. Perhaps rescuing ActiveRecord::RecordNotFound on your ApplicationController

当然,如果您有多个控制器并且需要在许多地方重复这些控制器,您应该使用更通用的方法。也许在ApplicationController上救出ActiveRecord :: RecordNotFound

#1


0  

There are two different cases you need to take care of

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

  • a wrong path
  • 错误的道路

  • a wrong resource
  • 错误的资源

For the first one, you can add a global match rule at the end of the routes.

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

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

Then you should handle the missing resources in your controllers.

然后,您应该处理控制器中缺少的资源。

eg

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

Of course if you have multiple controllers and need to repeat that in many places you should use a more general approach. Perhaps rescuing ActiveRecord::RecordNotFound on your ApplicationController

当然,如果您有多个控制器并且需要在许多地方重复这些控制器,您应该使用更通用的方法。也许在ApplicationController上救出ActiveRecord :: RecordNotFound