如何重定向到routes.rb中的404页面?

pit*_*4eg 9 redirect ruby-on-rails

如何将不正确的URL重定向到routes.rb中的404页面?现在我使用2个示例代码:

# example 1
match "/go/(*url)", to: redirect { |params, request| Addressable::URI.heuristic_parse(params[:url]).to_s }, as: :redirect, format: false

# example 2
match "/go/(*url)", to: redirect { |params, request| Addressable::URI.heuristic_parse(URI.encode(params[:url])).to_s }, as: :redirect, format: false
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在'url'参数中使用俄语单词时,在第一个例子中我得到500页(坏URI),在第二个 - 我得到重定向到stage.example.xn - org-yedaa​​a1fbbb/

谢谢

Ric*_*eck 27

如果你想要自定义错误页面,你最好看看我几周前写的这个答案


您需要几个重要元素来创建自定义错误路由:

- > 添加自定义错误处理程序application.rb:

# File: config/application.rb
config.exceptions_app = self.routes
Run Code Online (Sandbox Code Playgroud)

- > 在您的路线中创建/404路线routes.rb:

# File: config/routes.rb
if Rails.env.production?
   get '404', :to => 'application#page_not_found'
end
Run Code Online (Sandbox Code Playgroud)

- > 添加actions到应用程序控制器以处理这些路由

# File: app/controllers/application_controller.rb
def page_not_found
    respond_to do |format|
      format.html { render template: 'errors/not_found_error', layout: 'layouts/application', status: 404 }
      format.all  { render nothing: true, status: 404 }
    end
  end
Run Code Online (Sandbox Code Playgroud)

这显然是相对基础的,但希望它会给你更多关于你能做什么的想法


小智 5

最简单的方法是确保您的路由不匹配错误的 URL。默认情况下,Rails 会为不存在的路由返回 404。

如果您不能这样做,则默认 404 页面位于,/404以便您可以重定向到该位置。但是,这里要记住的是,这种类型的重定向将执行 301 永久重定向而不是 302。这可能不是您想要的行为。为此,您可以执行以下操作:

match "/go/(*url)", to: redirect('/404')
Run Code Online (Sandbox Code Playgroud)

相反,我建议在您的操作中设置一个 before 过滤器,而不是引发未找到的异常。我不确定这个异常是否在 Rails 4 中的同一个地方,但我目前正在使用 Rails 3.2:

raise ActionController::RoutingError.new('Not Found')
Run Code Online (Sandbox Code Playgroud)

然后您可以在控制器中进行任何处理和 URL 检查(如果需要对 URL 格式进行复杂的检查)。