【问题标题】:rails app not redirecting unkown url to 404 pagerails 应用程序不会将未知 url 重定向到 404 页面
【发布时间】:2020-12-29 20:42:20
【问题描述】:

我的 rails 6 应用程序没有将未知 url 重定向到默认的 rails 404 页面。 相反,它会在浏览器上显示重定向错误。 我应该在路由文件中添加一些代码吗?默认情况下,此功能不是与新的 rails 安装一起提供的吗?可能出了什么问题?

routes.rb

  Rails.application.routes.draw do
  resources :messages, only: [:new, :create]
  root 'static_pages#home'
  get  '/about',   to: 'static_pages#about'
  post "static_pages/home"
  post "static_pages/go_tafqit"

  constraints(subdomain: '') do
    get "(*x)" => redirect { |params, request|
      URI.parse(request.url).tap { |x| x.host = "#{x.host}" }.to_s
    }
  end
  end

application_Controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

【问题讨论】:

  • 在尝试查找 404 页面时可能无法解决设置问题,但如果没有任何相关代码则无法判断。可能它也发生在本地,在那里进行测试,然后您可以在日志中看到导致它不断重定向的原因
  • 它确实也发生在本地。当我输入无效的网址时,它会继续获取它。在 2020 年 12 月 27 日 01:54:13 +0200 开始为 ::1 获取“/abouts” 在 2020 年 12 月 27 日 01:54:14 +0200 开始为 ::1 获取“/abouts” 开始获取“/ abouts" for ::1 at 2020-12-27 01:54:14 +0200 ...不断生成该行,直到我停止服务器..
  • 您的应用程序中是否有任何可能导致无限重定向的包罗万象?
  • 你能分享任何与重定向相关的代码吗? /about 是您应用的有效 URL,还是您输入的无效 URL?
  • @max 不,什么都不知道

标签: ruby-on-rails http-status-code-404


【解决方案1】:

我使用这个解决方案进行 404 渲染:

match "*path", to: "errors#path_not_found", via: :all

  • “errors”是处理不同类型错误的控制器
  • "path_not_found" -> 是控制器的渲染方法和 要呈现的静态页面

你“可能”使用“get”而不是匹配(也可以删除“via::all”),但我使用“match”来捕获来自机器人的所有垃圾请求(get、patch、post、delete) .

【讨论】:

    【解决方案2】:

    我在 routes.rb

    中添加了以下行
    get '*path' => redirect('/404.html')
    

    并删除

    constraints(subdomain: '') do
        get "(*x)" => redirect { |params, request|
          URI.parse(request.url).tap { |x| x.host = "#{x.host}" }.to_s
        }
    

    现在工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 2019-05-11
      • 2019-03-03
      • 1970-01-01
      相关资源
      最近更新 更多