【问题标题】:How redirect to 404 page in routes.rb?如何重定向到 routes.rb 中的 404 页面?
【发布时间】:2023-03-18 00:57:02
【问题描述】:

如何将不正确的 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

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

谢谢

【问题讨论】:

  • 您能否提供一些您尝试使用的示例 URL?
  • 一些样本:stage.example.org/go/газета stage.example.org/go/газета.рф
  • 如果你想从控制器内重定向到 404 你也可以使用redirect_to("/404") && return

标签: ruby-on-rails redirect


【解决方案1】:

如果您想要自定义错误页面,最好查看我几周前写的this answer


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

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

# File: config/application.rb
config.exceptions_app = self.routes

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

# File: config/routes.rb
if Rails.env.production?
   get '404', :to => 'application#page_not_found'
end

-> 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

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

【讨论】:

    【解决方案2】:

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

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

    match "/go/(*url)", to: redirect('/404')
    

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

    raise ActionController::RoutingError.new('Not Found')
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2012-10-01
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多