我需要在Rails应用程序中为返回X-Frame-Options
的页面设置404 - Not Found
HTTP头,但是我不知道该怎么做。我无法使用rails设置这些标题,我发现了一个可能的原因here。但是,我也不知道如何使用Web服务器设置它们,因为我正在使用Puma。
我的ClickJacked
页中实际上没有404 - not found
可以包含的任何内容,但是外部安全组织仍然要求我这样做。
答案 0 :(得分:0)
在Rails中,异常由config.exceptions_app
处理。默认应用程序只是从公共目录中呈现静态html文件,但这可以是任何符合机架要求的应用程序。
符合Rack的应用程序的最基本示例是:
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