如何使用Rails / Puma为404找不到的页面设置HTTP标头

问题描述 投票:0回答:1

我需要为在Rails应用程序中返回X-Frame-Options的页面设置404 - Not Found HTTP标头,但是我不知道该怎么做。我无法使用rails设置这些标题,我发现了一个可能的原因here。但是,我也不知道如何使用Web服务器设置它们,因为我正在使用Puma。

我在ClickJacked页面中实际上没有任何可以作为404 - not found的东西,但是外部安全组织仍然要求我这样做。

ruby-on-rails puma x-frame-options
1个回答
0
投票

在Rails中,异常由config.exceptions_app处理。默认应用程序仅从公共目录中呈现静态html文件,但这可以是任何符合机架要求的应用程序。

与机架兼容的应用程序的最基本示例是:

app = ->(env){  [ 404, { "Content-Type" => "text/plain", "X-Frame-Options" => "some value" }, ["Oh no I cant find it!"] ] }

它接受一个参数(一个哈希)并返回一个数组(状态,标头,正文)。

Rails路由和ActionController::Metal(以及您的所有控制器)都是机架兼容的应用程序,甚至是config/application.rb。实际上,Rails只是Rack应用程序的俄罗斯玩偶方案。

如果您想通过自己的路线来解决这个问题,可以做:

# config/application.rb
config.exceptions_app = self.routes
# config/routes.rb
get '/404', to: "errors#not_found"
get '/422', to: "errors#unprocessable_entity"
get '/500', to: "errors#internal_error"
class ErrorsController < ActionController::Base
  before_action do
    response.set_header('X-Frame-Options', 'HEADER VALUE')
  end

  def not_found
    respond_to do |format|
      format.html { render file: Rails.root.join('public', '404.html'), layout: false, status: :not_found }
    end
  end

  def unprocessable_entity 
    respond_to do |format|
      format.html { render file: Rails.root.join('public', '422.html'), layout: false, status: :unprocessable_entity }
    end
  end

  def internal_error
    respond_to do |format|
      format.html { render file: Rails.root.join('public', '500.html'), layout: false, status: :internal_server_error }
    end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.